How to add a new object with AngularJS and mongoDB - angularjs

I'm using NodeJS, ANgularJS, and MongoDB with mongoose to make a website. I'm having some trouble adding an object in mongoDB. The name of the object is Todo.
Here are the models of Todo:
var mongoose = require('mongoose');
var TodoSchema = new mongoose.Schema({
name: String,
password : String,
completed: Boolean,
note: String
});
module.exports = mongoose.model('Todo', TodoSchema);
In the controller I create a new Todo and push it
angular.module('app').controller('Connexion', ['$scope', 'Todos','$location', function($scope,Todos, $location) {
$scope.editing = [];
$scope.todos = Todos.query();
$scope.save = function() {
var todo = new Todos({ name: "test", password: "test", completed: false });
$scope.todos.push(todo);
Todos.save($scope.todo);
}
}]);
This is my html page, each time I click on the button I Have a new todo created and it's displayed on screen:
<button ng-click="save()">Creer POST </button>
<ul>
<li ng-repeat="todo in todos">
{{todo.name}}
{{todo.password}}
</li>
</ul>
But I have a problem, the new object is not added on the database. How can I do it?
This is my files in the back-end :
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. */
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos */
router.post('/', function(req, res, next) {
Todo.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id */
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /todos/:id */
router.put('/:id', function(req, res, next) {
Todo.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id */
router.delete('/:id', function(req, res, next) {
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
And if this can help this the back-end file app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var Post = require('./models/Post.js');
var routes = require('./routes/index');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', function(req, res, next){
res.sendFile(__dirname + '/public/index.html');
});
var found = ['DB Connection not yet established. Try again later. Check the console output for error messages if this persists.'];
module.exports = app;

$scope.todo from Todos.save($scope.todo); is not defined so this is why you might not manage to save anything

Related

Passport Authentication success but does not redirect and gives 500 error

I am learning mean stack by making a social media web app like twitter
But at the time of signup or login i am getting success and a user also was created in database but the page does not redirects and gives error 500
The following is the code
App.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
require('./models/models.js');
var index = require('./routes/index');
var api = require('./routes/api');
var authenticate = require('./routes/authenticate')(passport);
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/chirp-test');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(passport.initialize());
app.use(passport.session());
var initPassport = require('./passport-init');
initPassport(passport);
app.use('/', index);
app.use('/auth', authenticate);
app.use('/api', api);
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
authenticate.js
var express = require('express');
var router = express.Router();
module.exports = function(passport){
router.get('/success', function(req, res){
res.send({state: 'success', user: req.user ? req.user : null});
});
router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password"});
});
//log in
router.post('/login', passport.authenticate('login', {
successRedirect: '/auth/success/',
failureRedirect: '/auth/failure'
}));
//sign up
router.post('/signup', passport.authenticate('signup', {
successRedirect: '/auth/success',
failureRedirect: '/auth/failure'
}));
//log out
router.get('/signout', function(req, res) {
req.logout();
res.redirect('/');
});
return router;
}
passport-init.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bCrypt = require('bcrypt-nodejs');
var mongoose = require('mongoose');
var User = mongoose.model('User');
var Post = mongoose.model('Post');
module.exports = function(passport){
passport.serializeUser(function(user, done) {
return done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user){
if(err){
return done(err, false);
}
if(!user){
return done('User not found', false);
}
return done(user, true);
})
});
passport.use('login', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
User.findOne({'username': username}, function(err, user){
if(err){
return done(err, false);
}
if(!user){
return done('Username does not exist ', false);
}
if(!isValidPassword(user, password)){
return done('Incorrect password', false);
}
return done(null, user);
});
}
));
passport.use('signup', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done) {
User.findOne({'username' : username}, function(err, user){
if(err){
return done(err, false);
}
if(user){
return done('Username already taken', false);
}
var newUser = new User();
newUser.username = username;
newUser.password = createHash(password)
newUser.save(function(err, user){
if(err){
return done(err, false);
}
console.log('Successfully signed up User ' + username);
return done(null, newUser);
});
});
})
);
var isValidPassword = function(user, password){
return bCrypt.compareSync(password, user.password);
};
var createHash = function(password){
return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
};
};
The error is somewhere in your passport-init.js where you invoke done() with a string as a first argument, e.g. done('User not found', false)
What you want to do instead is throw an actual error:
done(new Error('User not found'), false);
and then handle it later. Once you find the error you can find the reason for redirect to (not) work.

Cannot POST /api/register in Node Js

I am new at here and I am getting Can not post /api/register error in postman and 404 not found in console, I have checked all the possible question answers. Please assist me as soon as possible.
Thanks in advance.
The auth.controller.js file
var express = require ('express'); //EXPRESS Package
var route = express.Router(); //define our app using express
// var userModel = require('../model/user.model');
// var session = require('express-session');
var bodyParser = require('body-parser');// get body-parser
route.use(bodyParser.json()); // for parsing application/json
route.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
/**
*
* Register user
*/
route.post('/api/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/api/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
module.exports = route;
=========================================================================
The server.js File
var express = require ('express'); //EXPRESS Package
var app = express(); //define our app using express
var cors = require('cors');
var session = require('express-session');
var bodyParser = require('body-parser');// get body-parser
// var morgan = require('morgan'); //use to see requests
// var assert = require('assert');
// var path = require('path');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cors());
/**
* Header Control
*/
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,PATCH");
res.header('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version');
next();
} );
//routes
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
// app.use('/api/users', require('./controllers/users.controller'));
// app.get('/api', function (req, res) {
// res.send('/api/login');
// } );
// start server
var server = app.listen(8001, 'localhost', function () {
console.log('Server listening at http://' + server.address().address + ':' + server.address().port);
});
// module.exports = app;
When you use
app.use('/api/register', require('./controllers/auth.controller'));
Your application routes everything that comes to /api/register into require('./controllers/auth.controller'). Then require('./controllers/auth.controller') checks the remainder of the url for /api/register or /api/login, routes the request to the respective middleware if your router gets a match.
In other words, you need to post to /api/register/api/register in order to reach your desired middleware.
For a quick solution:
You should delete
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
and replace it with:
app.use('/', require('./controllers/auth.controller'));
For a better one:
You should delete
app.use('/api/register', require('./controllers/auth.controller'));
app.use('/api/login', require('./controllers/auth.controller'));
and replace it with:
app.use('/api', require('./controllers/auth.controller'));
in your app.js and also in your auth.controller.js you should replace:
route.post('/api/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/api/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
with:
route.post('/register', function (req, res) {
console.log(req.body);//res.sendStatus(200);
// userModel.create(req.body).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});
/**
*
* Login user
*/
route.post('/login', function (req, res) {
// userModel.authenticate(req.body.email, req.body.password).then( function () {
// res.sendStatus(200);
// }).catch( function (err) {
// res.status(400).send(err);
// });
});

meaning of parameters of function such as “/” res,req,next

I try to understand the code of a friend and I connect to js and nodejs for the first time,I want to know the meaning of "/" , req res next.
here is the code
in routes/task.js
var express = require('express');
var router = express.Router();
var Task = require('../models/task');
router.post("/", function(req, res, next){
var task = req.body;
Task.create(task, function(err, task){
if (err) {
return res.status(400).send("err in post /task");
} else {
return res.status(200).json(task);
}
});
});
router.get("/", function(req, res, next){
Task.find({}, function(err, tasks){
if(err){
return res.status(400).send("err in get /task");
}else{
console.log(tasks);
return res.status(200).json(tasks);
}
})
});
module.exports = router;
Task is a data module exports in models/task.js
var mongoose = require('mongoose');
var TaskSchema = new mongoose.Schema({
title: String,
create_at: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model("Task", TaskSchema);
This is to attach HTTP method request handlers using Express's router object for the webapp.

How to render data using Express 4 + Pug/Jade + Angularjs

I'm starting learning Express and Angularjs. In the project, I want to render HTML at the server side and bind data via Angularjs but it didnt work. I saw that ng-repeat is disable in browser
<body ng-app="photoApp" class="ng-scope">
<h1>Express</h1>
<p>Welcome to Express</p>
<!-- ngView: -->
<div ng-view="" class="ng-scope">
<div id="photos" class="ng-scope">
<!-- ngRepeat: photo in vm.photos -->
</div>
</div>
</body>
, therefore no data is showed. Please help me to fix that, thanks in advanced!
Project Structure
photo
--public
----javascript
------lib
------photoApp.js
--routes
----index.js
----photo.js
--views
----partials
------photo-list.pug
----error.pug
----index.pug
----layout.pug
--app.js
Server-side code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var photos = require('./routes/photos');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/photos', photos);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/partials/:name', function(req, res, next){
var name = req.params.name;
res.render('partials/' + name);
});
module.exports = router;
photos.js
var express = require('express');
var router = express.Router();
var photos = [];
photos.push({
name: 'Node.js Logo',
path: 'http://nodejs.org/images/logos/nodejs-green.png'
});
photos.push({
name: 'Ryan Speaking',
path: 'http://nodejs.org/images/ryan-speaker.jpg'
});
router.get('/api/get-all', function(req, res) {
res.json(photos);
});
router.get('/', function(req, res) {
res.render('photos');
});
module.exports = router;
layout.pug
doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
script(src='javascripts/lib/angular.js')
script(src='javascripts/lib/angular-route.js')
script(src='javascripts/photoApp.js')
body(ng-app="photoApp")
block content
index.pug
extends layout
block content
h1= title
p Welcome to #{title}
div(ng-view)
photo-list.pug
#photos
.photos(ng-repeat="photo in vm.photos")
h2 {{photo.name}}
img(src="{{photo.path}}")
Client-side code:
photoApp.js
var photoApp = angular.module('photoApp', ['ngRoute']);
photoApp.controller('PhotoListController', PhotoListController);
photoApp.config(['$routeProvider', function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'partials/photo-list',
controller: 'PhotoListController',
controllerAs: 'vm'
})
.otherwise({
redirectTo: '/'
});
}]);
function PhotoListController($scope, $http) {
var vm = this;
vm.getAllPhotos = getAllPhotos;
function getAllPhotos(){
$http.get('/photos/api/get-all')
.success(function(response) { vm.photos = response.photos; })
.error(function() { console.log('Error when getting all photos'); });
}
}

Using $resource to delete from database

I'm having trouble getting my head around $resource. I'm trying to apply a delete method to remove a MongoDB database entry when user presses a delete button. I am using Angular 1.4 with Express and Mongoose.
Here is my HTML:
<body ng-app="polls" ng-controller="PollsCtrl">
Polls:
<ul>
<li ng-repeat="question in questions">
{{ question.questionName }}
<button ng-click="deletePoll(question._id, $index)">Delete</button>
</li>
</ul>
...
Here's the client-side controller:
"use strict";
var app = angular.module('polls', ['ngResource']);
app.controller('PollsCtrl', function ($scope, $resource) {
var Poll = $resource('/api/polls');
var PollID = $resource('/api/polls/:pollID');
Poll.query(function (results) {
$scope.questions = results;
});
$scope.questions = [];
$scope.questionName = '';
$scope.addPoll = function () {
var poll = new Poll();
poll.questionName = $scope.questionName;
poll.$save(function (result) {
$scope.questions.push(result);
$scope.questionName = '';
});
};
$scope.deletePoll = function (id, index) {
var poll = new PollID();
poll.$remove(function () {
$scope.questions.splice(index, 1);
});
};
});
here's the server file including the remove method:
var express = require('express');
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();
mongoose.connect('mongodb://localhost/poll-app');
app.use('/controllers', express.static(__dirname + '/controllers'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/polls', function (req, res) {
res.sendFile(path.join(__dirname + '/polls.html'));
});
app.get('/add-poll', function (req, res) {
res.sendFile(path.join(__dirname + '/add-poll.html'));
});
var pollSchema = new mongoose.Schema({questionName: String});
var Poll = mongoose.model('Poll', pollSchema);
var creater = function (req, res) {
var poll = new Poll(req.body);
poll.save(function (err, result) {
if (err) throw err;
res.json(result);
})
};
var list = function (req, res) {
Poll.find({}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
var remove = function (req, res) {
console.log(req.params);
var poll = new Poll(req.body);
poll.remove({_id: req.params}, function (err, result) {
if (err) throw err;
res.json(result);
});
};
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.post('/api/polls', creater);
app.get('/api/polls', list);
app.delete('/api/polls/:pollID', remove);
app.listen(3000, function () {
console.log('HI');
});
I'm pretty sure the error lies in the server's remove() method. When i test this, i actually get:
DELETE http://localhost:3000/api/polls 404 (Not Found)
as though it isn't routing to where i want it to.
poll.$remove({pollID:id}, function () {
$scope.questions.splice(index, 1);
})
in your case, I think it's better to use $http:
$http.delete('/api/polls/pollID/'+req.params).
This way, you don't have to get the object before delete

Resources