Integrate angularjs with node api? - javascript

I have my node routes as below
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
//var morgan = require('morgan'); // log requests to the console (express4)
//var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override');
var fs = require('fs');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = require('./models/users');
var Dummy = require('./models/dummycar');
//app.use(express.static(__dirname + '/')); // set the static files location /public/img will be /img for users
//app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
// get users list
app.get('/api/users',function(req, res) {
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
//create users
app.post('/api/users', function(req, res) {
var user = new User();
user.username = req.body.username;
user.password = req.body.password;
user.save(function(err) {
if (err)
res.send(err);
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
});
});
//create cars
app.post('/api/cars', function(req, res) {
var dummy = new Dummy();
dummy.name = req.body.name;
dummy.brand = req.body.brand;
dummy.class = req.body.class;
dummy.price = req.body.price;
dummy.available = req.body.available;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("sucess");
});
});
//list cars
app.get('/api/cars',function(req, res) {
Dummy.find(function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
//list cars by available
app.get('/api/cars/available',function(req, res) {
Dummy.find({available:'true'},function(err, dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by class
app.get('/api/cars/:classtype',function(req, res) {
Dummy.find({class:req.params.classtype}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// list cars by price
app.get('/api/cars/price/:startvalue/:endvalue',function(req, res) {
Dummy.find({price:{$gte:req.params.startvalue,$lte:req.params.endvalue}}, function(err,dummys) {
if (err)
res.send(err);
res.json(dummys);
});
});
// booking option by sending date and name
app.get('/api/cars/book/:nametype',function(req, res) {
Dummy.findOne({name:req.params.nametype}, function(err, dummy) {
if (err)
res.send(err);
dummy.available = false;
dummy.save(function(err) {
if (err)
res.send(err);
res.send("updated");
});
});
});
// user authentication
app.get('/api/users/:usernametype/:passwordtype',function(req, res) {
User.findOne({$and:[{username:req.params.usernametype},{password:req.params.passwordtype}]}, function(err, user) {
if (err)
res.send(err);
else {
if (user == null)
res.send(false);
else
res.send(true);
}
});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
//app.use('/api', router);
// application -------------------------------------------------------------
app.get('*', function(req, res) {
res.sendfile('./view/intro.html'); // load the single view file (angular will handle the page changes on the front-end)
});
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('server running on ' + port);
My model are
//dummycar.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var dummySchema = new Schema({
name: {
type: String,
required: true
},
brand: {
type: String
},
class: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
available: {
type: Boolean,
required: true
},
dateavailable: {
type: Date,
default:Date.now }
});
module.exports = mongoose.model('Dummy', dummySchema);
//user.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', userSchema);
But i don't how to call them from angular.js
I have my intro.html as below
<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<base href="/">
<title>Starter Node and Angular</title>
<!-- CSS -->
<link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css"> <!-- custom styles -->
<!-- JS -->
<script src="libs/angular/angular.min.js"></script>
<script src="libs/angular-route/angular-route.min.js"></script>
<!-- ANGULAR CUSTOM -->
<script src="js/controllers/MainCtrl.js"></script>
<script src="js/controllers/NerdCtrl.js"></script>
<script src="js/services/NerdService.js"></script>
<script src="js/appRoutes.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-app="sampleApp" ng-controller="NerdController">
<div class="container">
<!-- HEADER -->
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="/">Stencil: Node and Angular</a>
</div>
<!-- LINK TO OUR PAGES. ANGULAR HANDLES THE ROUTING HERE -->
<ul class="nav navbar-nav">
<li>Nerds</li>
</ul>
</nav>
<!-- ANGULAR DYNAMIC CONTENT -->
<div ng-view></div>
</div>
</body>
</html>
I would like to call them when user click each link. If some one could help me developing angularjs services.

Best would be to create a service but you can do it in the ctrl aswell
// users.service.js
var userService = angular.module('app.userService', ['ngResource'])
.factory('users', function ($http, $q) {
var that = this;
this.data = {};
var url = '';
var factory = {
get: get
};
function get() {
url = '/api/users';
var defer = $q.defer();
$http.get(url).
success(function (data, status, headers, config) {
defer.resolve(data);
}).
error(function (data, status, headers, config) {
defer.reject(data);
});
return defer.promise;
};
});
// some.controller.js
angular.module('app.somectrl', ['app.userService'])
.controller(someController);
function someController(userService) {
userService.get().then(function (res) {
// do sth
}, function (err) {
// handle error
});
}

Related

Node js form submit leads to following error - Error: Cannot POST / [duplicate]

This question already has an answer here:
Node js form submit TypeError: Cannot set property 'userId' of undefined
(1 answer)
Closed 2 years ago.
I have added login/registration features to my application. These added features, when used in a separate folder work perfectly, as well as my application on its own. However, adding the login/registration features to my perfectly working application has led me to this error. This would happen when I would type in my details on the login page and click the register button (registering an account) to receive the following message on my browser tab 'Error: Cannot POST /' . I cannot understand why I am getting this error. Here is the code I am working with right now that gets me this errorr. I am new to node js etc so I apologise if this is simple! I am using MongoDB Compass Community as my database. Also, apologies for a lot of code but this is all the code necessary to use my login/registration features.
Folder/File Structure
controllers/employeeController.js
const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Employee = mongoose.model('Employee');
const Task = require('../models/task');
var User = require('../models/user');
router.get('/login', (req, res) => {
res.render("employee/login");
});
//POST route for updating data
router.post('employee/login', function (req, res, next) {
// confirm that user typed same password twice
if (req.body.password !== req.body.passwordConf) {
var err = new Error('Passwords do not match.');
err.status = 400;
res.send("passwords dont match");
return next(err);
}
if (req.body.email &&
req.body.username &&
req.body.password &&
req.body.passwordConf) {
var userData = {
email: req.body.email,
username: req.body.username,
password: req.body.password,
}
User.create(userData, function (error, user) {
if (error) {
return next(error);
} else {
req.session.userId = user._id;
return res.redirect('/profile');
}
});
} else if (req.body.logemail && req.body.logpassword) {
User.authenticate(req.body.logemail, req.body.logpassword, function (error, user) {
if (error || !user) {
var err = new Error('Wrong email or password.');
err.status = 401;
return next(err);
} else {
req.session.userId = user._id;
return res.redirect('/profile');
}
});
} else {
var err = new Error('All fields required.');
err.status = 400;
return next(err);
}
})
// GET route after registering
router.get('/profile', function (req, res, next) {
User.findById(req.session.userId)
.exec(function (error, user) {
if (error) {
return next(error);
} else {
if (user === null) {
var err = new Error('Not authorized! Go back!');
err.status = 400;
return next(err);
} else {
return res.send('<h1>Name: </h1>' + user.username + '<h2>Mail: </h2>' + user.email + '<br><a type="button" href="/logout">Logout</a>')
}
}
});
});
// GET for logout logout
router.get('/logout', function (req, res, next) {
if (req.session) {
// delete session object
req.session.destroy(function (err) {
if (err) {
return next(err);
} else {
return res.redirect('/');
}
});
}
});
module.exports = router;
models/user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
required: true,
}
});
//authenticate input against database
UserSchema.statics.authenticate = function (email, password, callback) {
User.findOne({ email: email })
.exec(function (err, user) {
if (err) {
return callback(err)
} else if (!user) {
var err = new Error('User not found.');
err.status = 401;
return callback(err);
}
bcrypt.compare(password, user.password, function (err, result) {
if (result === true) {
return callback(null, user);
} else {
return callback();
}
})
});
}
//hashing a password before saving it to the database
UserSchema.pre('save', function (next) {
var user = this;
bcrypt.hash(user.password, 10, function (err, hash) {
if (err) {
return next(err);
}
user.password = hash;
next();
})
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
server.js
require('./models/employee.model');
require('./models/task');
const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const logger = require('morgan');
const favicon = require('serve-favicon');
var app = express();
var mongoose = require('mongoose');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/testForAuth', { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false }, (err) => {
if (!err) { console.log('MongoDB Connection Succeeded.') }
else { console.log('Error in DB connection : ' + err) }
});
var db = mongoose.connection;
//handle mongo error
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
// we're connected!
});
//use sessions for tracking logins
app.use(session({
secret: 'work hard',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
const employeeController = require('./controllers/employeeController');
var app = express();
//setting up morgan middleware
app.use(logger('dev'));
app.use(bodyparser.urlencoded({
extended: true
}));
app.use(bodyparser.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('hbs', exphbs({ extname: 'hbs', defaultLayout: 'mainLayout', layoutsDir: __dirname + '/views/layouts/' }));
app.set('view engine', 'hbs');
//serving blank favicon to keep from throwing 404 errors
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
//setting up static path for serving static files
app.use(express.static(path.join(__dirname, 'public')));
//Bringing in the routes
const index = require('./routes/index');
const api = require('./routes/api');
app.use('/', index);
app.use('/api', api);
app.listen(3000, () => {
console.log('Express server started at port : 3000');
});
app.use('/employee', employeeController.router);
views/employee/login.hbs (handlebars)
<!DOCTYPE html>
<html>
<head>
<title>Register Login with Authentication</title>
<!--Custom Theme files-->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="Register Login Widget template Responsive, Login form web template,Flat Pricing tables,Flat Drop downs Sign up Web Templates, Flat Web Templates, Login Signup Responsive web template, SmartPhone Compatible web template, free WebDesigns for Nokia, Samsung, LG, SonyEricsson, Motorola web design" />
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!-- Custom Theme files -->
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<!--web-fonts-->
<link href='//fonts.googleapis.com/css?family=Jura:400,300,500,600' rel='stylesheet' type='text/css'>
<!--//web-fonts-->
</head>
<body>
<h1>Test Authentication</h1>
<div class="main">
<div class="w3">
<div class="signin-form profile">
<h3>Login</h3>
<div class="login-form">
<form action="/" method="post">
<input type="text" name="logemail" placeholder="E-mail" required="">
<input type="password" name="logpassword" placeholder="Password" required="">
<div class="tp">
<input type="submit" value="LOGIN NOW">
</div>
</form>
</div>
</div>
</div>
<div class="agile">
<div class="signin-form profile">
<h3>Register</h3>
<div class="login-form">
<form id="login" action="/" method="post" onsubmit="event.preventDefault(); validateMyForm();">
<input type="text" name="email" placeholder="E-mail" required="">
<input type="text" name="username" placeholder="Username" required="">
<input type="password" name="password" placeholder="Password" id="password" required="" >
<input type="password" name="passwordConf" placeholder="Confirm Password" id="password_conf" required="">
<input type="submit" value="REGISTER">
</form>
</div>
<p> By clicking register, I agree to your terms</p>
</div>
</div>
<div class="clear"></div>
<!--//signin-form-->
</div>
<script type="text/javascript">
var passWordField = document.getElementById('password')
var passWordConfirmField = document.getElementById('password_conf')
var form = document.getElementById('login')
function validateMyForm(){
if(passWordField.value != passWordConfirmField.value){
alert("Passwords do not match. Please try again.");
} else {
form.submit()
}
}
</script>
</body>
</html>
You are missing the first slash in the route post 'employee/login'
You just have to change this line:
router.post('employee/login', function (req, res, next) {
To be like that:
router.post('/employee/login', function (req, res, next) {
this should fix the route.
In your form you must change the action property to point to the route that handles the post request.
<form action="/employee/login" method="post">
That should fix.

Angular app hangs when POST request is given, Chrome console gives error ERR_EMPTY_RESPONSE?

So I am a newbie in MEAN world. I am referring to this book Write Modern Web Apps With The Mean Stack Mongodb Express Angularjs and Node.js. So in this book, they teach us how to build a Twitter close using the MEAN stack. I have just copied the code from the book but it is not working. Can you help me out?
Package.json
{
"name": "socialapp",
"dependencies": {
"body-parser": "^1.13.0",
"mongoose": "^3.8.30"
}
}
server.js
var express = require('express')
var bodyParser = require('body-parser')
var Post = require('./models/post')
var app = express()
app.use(bodyParser.json())
app.get('/api/posts', function (req, res, next) {
Post.find(function(err, posts) {
if (err) { return next(err) }
res.json(posts)
})
})
app.post('/api/posts', function (req, res, next) {
var post = new Post({
username: req.body.username,
body: req.body.body
})
post.save(function (err, post) {
if (err) { return next(err) }
res.json(201, post)
})
})
app.listen(3000, function () {
console.log('Server listening on', 3000)
})
app.get('/', function (req, res) {
res.sendFile('layouts/posts.html', { root: __dirname });
})
db.js
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/social', function () {
console.log('mongodb connected')
})
module.exports = mongoose
models/post.js
var db = require('../db')
var Post = db.model('Post', {
username: { type: String, required: true },
body: { type: String, required: true },
date: { type: Date, required: true, default: Date.now }
})
module.exports = Post
layouts/posts.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.3.16/angular.min.js'></script>
</head>
<body ng-app='app'>
<div ng-controller='PostsCtrl' class='container'>
<h1>Recent Posts</h1>
<form role='form'>
<div class='form-group'>
<div class='input-group'>
<input ng-model='postBody' class='form-control' />
<span class='input-group-btn'>
<button ng-click='addPost()' class='btn btn-default'>Add Post</button>
</span>
</div>
</div>
</form>
<ul class='list-group'>
<li ng-repeat='post in posts' class='list-group-item'>
<strong>#{{ post.username }}</strong>
<span>{{ post.body }}</span>
</li>
</ul>
</div>
<script>
// create our app module
var app = angular.module('app', [])
// create the PostsCtrl module
// dependency inject $scope
app.controller('PostsCtrl', function ($scope,$http) {
$scope.addPost = function () {
if ($scope.postBody) {
$http.post('http://localhost:3000/api/posts', {
username: 'rahul23khanna',
body: $scope.postBody
}).success(function (post) {
$scope.posts.unshift(post)
$scope.postBody = null
})
}
}
// starting data
$http.get('http://localhost:3000/api/posts')
.success(function (posts) {
$scope.posts = posts
})
})
</script>
</body>
</html>

ExpressJs - Finding records matching route parameter

I have been building out a tagging system for my ExpressJS application and I have been able to create my routing to pick up on the individual tags that are used for my record, but the issue I am running into is trying to display content associated with the selected tag. For instance a record has a tag "Mouse", when clicked the route correctly goes to /tag/mouse, but I'm not sure if I should use a loop within my template to display only those values or if I should really be using a method within my route. I'm currently using nothing and the value being displayed on the tag page is undefined. I have a feeling the route method is what I am looking for.
Here is the main focus of my routes file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
console.log(req.body.tags);
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags.trim().split(","); // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res, blogpost) {
res.render('pages/blogpost-create', {
blogpost : blogpost
});
});
function getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.get('/tag/:blogpost_tags', function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/tag', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
Model:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var BlogPostSchema = new Schema({
title: String,
featureImage: String,
blogUrl: String,
author: String,
tagline: String,
category: String,
content: String,
tags: { type: Array, lowercase: true },
date: { type: Date, default: Date.now() }
});
BlogPostSchema.post('init', function (post) {
var date = new Date(post.date || Date.now() );
post.dateString = date.getMonth() + 1 + '/' + date.getDate() + '/' + date.getFullYear();
});
BlogPostSchema.plugin( mongoosePaginate );
var Blogpost = mongoose.model("Blogpost", BlogPostSchema);
module.exports = mongoose.model('Blogpost', BlogPostSchema);
Tag page (EJS):
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<header>
<% include ../partials/header %>
</header>
<div class="container">
<div class="col-md-12">
<%= blogpost.tags %>
</div>
</div>
<footer>
<% include ../partials/footer %>
</footer>
</body>
</html>

ExpressJS Link to Update Content

I am trying to be able to update my content via my editor, but I'm wondering what part of my application I should be modifying to be able to do this. I have a feeling that it is through the route file, but was wondering if there was a hyperlink method that I should be using from within my view to be able to generate my view with the content I want to edit.
Here is my route file:
var express = require('express');
var router = express.Router();
var passport = require('passport');
var blogDB = require('../config/blogDB.js');
var Blogpost = require('./models/blogModel.js');
var paginate = require('express-paginate');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
var AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
var S3_BUCKET = process.env.S3_BUCKET;
//index
router.use(paginate.middleware(10, 50));
router.route('/')
// START GET method
.get(function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/index', {
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
}); // END GET method
router.get('/sign_s3', function(req, res){
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.s3_object_name,
Expires: 60,
ContentType: req.query.s3_object_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
}
else{
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.s3_object_name
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
router.route('/admin/posts/create')
// START POST method
.post(function(req, res) {
console.log("New instance");
var blogpost = new Blogpost(); // create a new instance of a Blogpost model
blogpost.title = req.body.title; // set the blog title
blogpost.featureImage = req.body.featureImage; // set the blog image
blogpost.blogUrl = blogpost.title.toLowerCase().replace(/\s+/g,"-");
blogpost.author = req.body.author; // set the author name
blogpost.tagline = req.body.tagline; // set the tagline
blogpost.content = req.body.content; // set the blog content
blogpost.category = req.body.category; // set the category
blogpost.tags = req.body.tags; // set the tags
//Save Blog Post
blogpost.save(function(err) {
if (err)
res.send(err);
res.redirect(303, '/'); //NEEDS TO BE CHANGED
});
}) // END POST method
.get(isLoggedIn, function(req, res) {
res.render('pages/blogpost-create');
});
function getSearchCriteria(params) {
return {
blogUrl: params.blogpost_blogUrl
};
}
router.route('/blog/:blogpost_blogUrl')
.get(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOne(searchCriteria, function (err, blogpost) {
if (err)
res.send(err);
res.render('pages/blogpost', {
blogpost: blogpost
})
})
})
.put(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
var updated = getBlogpostUpdate(req.body)
Blogpost.findOneAndUpdate(searchCriteria, updated, function (err, updated) {
if (err)
res.send(err);
res.json({ message: 'Blog updated.' });
});
})
.delete(function (req, res) {
var searchCriteria = getSearchCriteria(req.params);
Blogpost.findOneAndRemove(searchCriteria, function (err, removed) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
//about
router.get('/about', function(req, res) {
res.render('pages/about');
});
//resume
router.get('/resume', function(req, res) {
res.render('pages/resume');
});
//portfolio
router.get('/portfolio', function(req, res) {
res.render('pages/portfolio');
});
//login
router.route('/login')
.get(function(req, res) {
res.render('pages/login.ejs', {
message: req.flash('loginMessage')
});
})
.post(passport.authenticate('local-login', {
successRedirect : '/admin',
failureRedirect : '/login',
failurFlash : true
}));
//sign up
/*
router.route('/signup')
.get(function(req, res) {
res.render('pages/signup.ejs', {
message: req.flash('signupMEssage')
});
})
.post(passport.authenticate('local-signup', {
successRedirect : '/admin',
failureRedirect : '/signup',
failurFlash : true
}));
*/
//admin dashboard
router.get('/admin', isLoggedIn, function(req, res, next) {
Blogpost.paginate({}, req.query.page, req.query.limit, function(err, pageCount, blogpost, itemCount) {
if (err) return next(err)
if (err)
res.send(err);
res.format({
html: function() {
res.render('pages/admin', {
user: req.user,
blogpost: blogpost,
pageCount: pageCount,
itemCount: itemCount
})
},
json: function() {
res.json({
object: 'blogpost',
has_more: paginate.hasNextPages(req)(pageCount),
data: blogpost
})
}
}); // END res.format(html, json)
}, {sortBy: {'date': -1} } ); // END Blogpost.paginate
});
//logout
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
//middleware to make sure user is logged in
// route middleware to make sure
function isLoggedIn(req, res, next) {
// if user is authenticated in the session, carry on
if (req.isAuthenticated())
return next();
// if they aren't redirect them to the home page
res.redirect('/');
}
module.exports = router;
Blogpost.ejs (Where I'm trying to create a link to edit the post):
<!doctype html>
<html>
<head>
<title>Node Authentication</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.2/css/bootstrap.min.css">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css">
</head>
<body>
<div class="container">
<div class="page-header">
<h1>Admin</h1>
<h2>Welcome user <%= user.local.email %></h2>
Logout
</div>
<div class="row">
<!-- LOCAL INFORMATION -->
<div class="col-sm-6">
<h3>New Post</h3>
<div class="well">
<h3><span class="fa fa-user"></span> Local</h3>
<p>
<strong>id</strong>: <%= user._id %><br>
<strong>email</strong>: <%= user.local.email %><br>
</p>
</div>
<h3><u>Published Blogposts</u></h3>
<% blogpost.forEach(function(blogpost) { %>
<h4><%= blogpost.title %> Edit</h4>
<% }); %>
</div>
</div>
</div>
</body>
</html>

Not being able to POST in MEAN single page app

I have only just started trying out NodeJS. Having a little experience with Angular, I thought of trying out a MEAN stack to-do app tutorial from scotch.
I understand what is happening and how angular, node and my view are supposed to be working together. But they just aren't. I've made sure not to miss anything. Here is my code.
Server.js is in the root folder
// server.js
// set up ========================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var mongodb = require('mongodb');
var morgan = require('morgan'); // log requests to the console (express4)
var bodyParser = require('body-parser'); // pull information from HTML POST (express4)
var methodOverride = require('method-override'); // simulate DELETE and PUT (express4)
// configuration =================
mongoose.connect('mongodb://<user>:<pass>#proximus.modulusmongo.net:27017/uwa8sIje'); // connect to mongoDB database on modulus.io
app.use(express.static(__dirname +'/public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended':'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(methodOverride());
// creating mongoose model ================================
var Todo = mongoose.model('Todo', {
text: String
});
// Todo is the mongo db. Creating API for CRUD in the db
//============================================================
app.get('/api/todos', function(req, res) {
Todo.find(function (err, todos) { //within 'get' we are looking for all the entries in the db
if(err) {
res.send(err) //checking for errors
}
res.json(todos); //response sends all listed todos in JSON
})
})
app.post('/api/todos', function(req, res) { //to post a new todo
Todo.create({ //creating a new post. information comes from AJAX request from Angular
text: req.body.text,
done: false
}, function(err, todo) { //checking errors
if(err) {
res.send(err);
}
Todo.find(function (err, todos) { //after post is added, find and display all existing todos again
if(err) {
res.send(err)
}
res.json(todos);
})
})
})
app.delete('/api/todos/:todo_id', function(req, res) { //delete a todo
Todo.remove({ //remove a todo from database
_id: req.params.todo_id, //todo id to be removed is provided by the request url(params)
}, function(err, todo) {
if(err) {
res.send(err);
}
Todo.find(function (err, todos) {
if (err) {
res.send(err)
}
res.json(todos);
})
})
})
//======================================================================
app.get('*', function(req,res) {
res.sendfile('./public/index.html') //load this single view file. angular will handle the
//page changes on the front end
})
// listen (start app with node server.js) ======================================
app.listen(8080);
console.log("App listening on port 8080");
My angular controller lies in the public folder along with my view
var Todoz = angular.module('Todoz', []);
function mainController($http, $scope) {
$scope.formData = {};
$http.get('/api/todos')
.success(function (data) {
$scope.todos = data;
console.log(data);
})
$scope.createTodo = function() {
$http.post('/api/todos', $scope.formData)
.success(function (data) {
$scope.formData = {};
$scope.todos = data;
})
.error(function (data) {
console.log('Error' + data)
})
}
$scope.deleteTodo = function(id) {
$http.delete('/api/todos/' + id)
.success(function (data) {
$scope.todos = data;
console.log(data);
})
.error(function (data) {
console.log(data)
});
};
Todoz.controller("mainController", mainController);
}
and my minimal view
<head>
<title>
To-Do-and-Node-To-Do
</title>
</head>
<body ng-app="Todoz">
<h1>The To-do-ist</h1>
<div ng-controller="mainController">
<div>
<input type="text" ng-model="formData.text"></input>
<button type="submit" ng-click="createTodo()">Submit</button>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="./core.js"></script>
</body>
When I start the server with 'nodemon server.js' my console logs a /GET request and the app shows on my port 8080. However when I try to post a new item from my text-box and expect it to console.log, it doesn't do anything. My browser console returns this
POST http://localhost:8080/api/todos net::ERR_CONNECTION_REFUSED angular.js:8632
Error core.js:23
POST http://localhost:8080/api/todos net::ERR_CONNECTION_REFUSED angular.js:8632
Error core.js:23
Please help. I have no clue what is going wrong.

Categories