Can't use passport.authenticate('local') - node.js

I posted question here cuz I my passport.authenticate('local') shows nothing, so I cannot use login function. I can activate singup api that I created, but somehow I cannot use my login api that I created as well.
Here is my code below.
var createError = require('http-errors');
var express = require('express');
var ejsMate = require('ejs-mate');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var config = require('./config')
var passport = require('passport')
// var session = require('express-session')
var homeRouter = require('./routes/home');
var usersRouter = require('./routes/users');
const mongoose = require('mongoose')
const url = config.mongoUrl
const connect = mongoose.connect(url)
connect.then((db) => {
console.log('Connected correctly to server')
}, (err) => {console.log(err)})
var app = express();
// view engine setup
//GET, POST, DELETE, PUT
app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize())
//localhost:3000/
app.use('/', homeRouter);
//localhost:3000/users
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')))
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var express = require('express');
const bodyParser = require('body-parser')
var User = require('../models/users')
var passport = require('passport')
var authenticate = require('../authenticate')
var router = express.Router();
router.use(bodyParser.json())
/* GET users listing. */
router.get('/', (req, res, next) => {
console.log("HAHA")
User.find({})
.then((Users) => {
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.json(Users)
}, (err) => next(err))
.catch((err) => next(err))
});
router.post('/signup', (req, res, next) => {
User.register(new User({username: req.body.username}),
req.body.password, (err, user) => {
if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
if(req.body.firstname)
user.firstname = req.body.firstname
if(req.body.lastname)
user.lastname = req.body.lastname
user.save((err, user) => {
if(err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
})
})
}
})
});
router.post('/login', passport.authenticate('local'), (req, res) => {
var token = authenticate.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, token: token, status: 'You are successfully logged in!'});
})
router.get('/logout', (req, res, next) => {
console.log(req.session)
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
module.exports = router;
router.post('/login', passport.authenticate('local') ---> show nothing it keep showing me an error
I need some advice and help.

Related

I keep getting "Login sessions require session support" when I try to use tokens

So I am following a tutorial on how to use JSON tokens and I am getting an error, it was working fine using sessions but I can't figure out why I am having trouble, it is the exact code
this is my authenticate.js file:
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("./models/user");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
const jwt = require("jsonwebtoken"); // used to create, sign, and verify tokens
const config = require("./config.js");
exports.local = passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
exports.getToken = function (user) {
return jwt.sign(user, config.secretKey, { expiresIn: 3600 });
}; // config.secretKey is a string of random numbers
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secretKey;
exports.jwtPassport = passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
console.log("JWT payload:", jwt_payload);
User.findOne({ _id: jwt_payload._id }, (err, user) => {
if (err) {
return done(err, false);
} else if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
})
);
exports.verifyUser = passport.authenticate("jwt", { session: false });
This is my app.js file (the main file):
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const config = require("./config");
const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const mongoose = require("mongoose");
const passport = require("passport");
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
useCreateIndex: true,
useFindAndModify: false,
useNewUrlParser: true,
useUnifiedTopology: true,
});
connect.then(
() => console.log("Connected correctly to server"),
(err) => console.log(err)
);
const app = express();
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser("12345-67890-09876-54321"));
app.use(passport.initialize());
app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use(express.static(path.join(__dirname, "public")));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
module.exports = app;
this is the routes/users.js file (I believe the problem is here because I can sign-up (create new users) but I can't login with the same users)
const express = require("express");
const User = require("../models/user");
const passport = require("passport");
const authenticate = require("../authenticate");
const router = express.Router();
/* GET users listing. */
router.get(
"/",
function (req, res, next) {
res.send('send users')
}
);
router.post("/signup", (req, res) => {
User.register(
new User({ username: req.body.username }),
req.body.password,
(err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
} else {
if (req.body.firstname) {
user.firstname = req.body.firstname;
}
if (req.body.lastname) {
user.lastname = req.body.lastname;
}
user.save((err) => {
if (err) {
res.statusCode = 500;
res.setHeader("Content-Type", "application/json");
res.json({ err: err });
return;
}
passport.authenticate("local")(req, res, () => {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
status: "Registration Successful!",
});
});
});
}
}
);
});
// I tried to add a console.log inside of the .post() route but it never reach it
router.post(
"/login",
passport.authenticate("local"),
(req, res) => {
const token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json({
success: true,
token: token,
status: "You are successfully logged in!",
});
}
);
router.get("/logout", (req, res, next) => {
if (req.session) {
req.session.destroy();
res.clearCookie("session-id");
res.redirect("/");
} else {
const err = new Error("You are not logged in!");
err.status = 401;
return next(err);
}
});
module.exports = router;
Basically, every time that i go to localhost:3000/users/login and send a POST request with the username and password, it tells me that I need to use express-session but I am trying to use tokens instead of session
The problem is caused when passport.authenticate('local') is called in routes/users.js file. It is a middleware that automatically calls req.login function in case correct username and password is provided.
The req.login() in turn, implements sessions in order to serialise the user in the session.
You can solve the issue by adding another parameter to passport.authenticate() as passport.authenticate('local', {session: false}. This ensures sessions are not implemented in the 'local' strategy and subsequently login can be performed.
Thanks, it helped me. You have to remove app.use(passort.session) from app.js and do
router.post('/login', passport.authenticate('local', { session: false }), (req, res) => {
var token = authenticate.getToken({ _id: req.user._id });
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({ success: true, token: token, status: 'You are successfully logged in!' });
});

error 404 while authenticating with passport js local

Really stuck on the same issue for much time. Tried many things but all to no use. Please help.
The register module works fine but the login doesn't. It returns 404 error upon hitting submit button. Attached are the appropriate code documents.
The login module is supposed to redirect to contactlist upon successful authentication.
Thank you very much!.
app.js
let createError = require('http-errors');
let express = require('express');
let path = require('path');
let cookieParser = require('cookie-parser');
let logger = require('morgan');
var bodyParser = require('body-parser');
let Login = require('../models/login')
let passport = require('passport');
let LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
//database setup
let mongoose = require('mongoose');
let DB = require('./db');
//point mongoose to the db URI
mongoose.connect(DB.URI);
let mongoDB = mongoose.connection;
mongoDB.on('error',console.error.bind(console,'Connection Error in Mongo'));
mongoDB.once('open',()=>{
console.log("Connected to MongoDB");
})
let indexRouter = require('../routes/index');
let usersRouter = require('../routes/users');
let loginRouter = require('../routes/login');
let authRouter = require('../routes/auth');
const exp = require('constants');
let app = express();
// view engine setup
app.set('views', path.join(__dirname, '../views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(express.static(path.join(__dirname, '../../public')));
app.use(express.static(path.join(__dirname,'../../node_modules')));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/', authRouter);
// passport config
passport.serializeUser(Login.serializeUser());
passport.deserializeUser(Login.deserializeUser());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error',{ title: 'error' });
});
module.exports = app;
auth.js
let express = require('express');
let router = express.Router();
let passport = require('passport');
let user = require('../models/user');
router.post('/register',(req,res,next)=>{
user.register(new user({
username:req.body.username,
}),
req.body.password,(err, newUser) =>{
if(err){
return res.redirect('/login/register')
}
else{
req.login(newUser,(err) => {
res.redirect('/login/contactlist')
})
}
}
)
});
router.post('/', passport.authenticate('local', { failureRedirect: '/login/contactlist' }),
function(req, res) {
res.redirect('/login/contactlist');
});
module.exports = router;
login.js
let express = require('express');
let router = express.Router();
let passport = require('passport');
/* GET index page. */
let Login = require('../models/login')
let Contact = require('../models/contact')
router.get('/', function(req, res, next) {
Login.find((err,loginList)=>{
if(err){
return console.error(err);
}
else {
//console.log(loginList);
res.render('login/login', { title: 'Login',loginList: loginList,user: req.user });
}
});
});
router.get('/register', function(req, res, next) {
res.render('login/register')
});
/* GET contactlist page. */
router.get('/contactlist', function(req, res, next) {
Contact.find((err,contactList)=>{
if(err){
return console.error(err);
}
else {
res.render('login/contactlist', { title: 'contactlist',contactList: contactList });
}
});
});
/* GET update page. */
router.get('/update/:id', function(req, res, next) {
let id = req.params.id;
Contact.findById(id, (err, contactToEdit) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
//show the edit view
res.render('login/update', {title: 'Update', contact:contactToEdit })
}
});
});
router.get('/delete/:id', function(req, res, next) {
let id = req.params.id;
Contact.remove({_id: id}, (err) => {
if(err)
{
console.log(err);
res.end(err);
}
else
{
// refresh the contacts list
res.redirect('/login/contactlist');
}
});
});
/* POST update page. */
router.post('/update/:id', function(req, res, next) {
let id = req.params.id
let newContact = Contact({
"_id":id,
"email":req.body.email,
"number": req.body.number,
"name":req.body.name
});
Contact.updateOne({_id: id},newContact,(err)=>{
console.log(newContact);
if(err){
console.log(err);
res.end(err);
}
else{
console.log(id)
console.log("POST update");
res.redirect('/login');
}
});
});
/* POST contactlist page. */
router.post('/contactlist', function(req, res, next) {
res.render('login/contactlist', { title: 'contactlist' });
});
module.exports = router;

Nodejs render view and template EJS

I two questions about render view,
Why It does not work? If i put res.render into if(error), it not render new site, but is still on current page.
And second question is, if I in ejs template view, I put <%= errors %> to display errors, and its does it work, is shown Error File Not Found
router.post('/create', function (req, res, next) {
var newUser = {
username: req.body.username,
password: req.body.password
}
req.checkBody('username', 'Login is required').notEmpty();
req.checkBody('password', 'Password is required').notEmpty();
var errors = req.validationErrors();
if(errors){
console.log(errors)
res.render('index',{
errors:errors
// console.log(errors)
// res.send(errors);
});
} else {
bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
if (err) {
console.log(err)
} else {
newUser.password = hash;
var user = new User(newUser);
user.save()
.then(function (User) {
res.send(User);
})
}
});
req.flash('success_msg', 'You are registered and can now login');
//res.redirect('/');
}
});
on console.log(errors) is
[ { param: 'username', msg: 'Login is required', value: undefined },
{ param: 'password',
msg: 'Password is required',
value: undefined } ]
The express render method can also return errors. Use the callback to determine whether this is happening and add a return to stop logic after the else statement from occurring.
var errors = req.validationErrors();
if(errors){
return res.render('index', { errors: errors }, function (err, html) {
if (err) console.error(err);
res.send(html);
});
}
bcrypt.hash(newUser.password, saltRounds, function (err, hash) {
if (err) {
console.log(err)
} else {
newUser.password = hash;
var user = new User(newUser);
user.save()
.then(function (User) {
res.send(User);
})
}
});
req.flash('success_msg', 'You are registered and can now login');
return res.redirect('/');
APP.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStategy = require('passport-local').Strategy;
var indexPage = require('./routes/index/index');
var productPage = require('./routes/product/product');
var userPage = require('./routes/user/user');
var categoryPage = require('./routes/category/category');
var filenotfound = require('./routes/error/error');
var mongoose = require('mongoose');
var Product = require('./model/product.model');
var Category = require('./model/category.model');
var User = require('./model/user.model');
var app = express();
mongoose.connect('mongodb://localhost/products', function (error) {
if (error) {
console.log('blad w polaczeniu')
} else {
console.log('connected');
//=========================CONNNNNNECTTTTTTEEEEEEDDDDDDDDDDDDDDDD======================//
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/assets', express.static('public'));
// 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(session({
secret: 'dadasdasdaxsax',
resave: true,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: function (param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect Flash
app.use(flash());
// Global Vars
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
});
app.use('/', indexPage);
app.use('/product', ensureAuthenticated, productPage);
app.use('/user', userPage);
app.use('/category', ensureAuthenticated, categoryPage);
app.use('/error', filenotfound);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
//req.flash('error_msg','You are not logged in');
res.redirect('/');
}
}
// 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 handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//=========================CONNNNNNECTTTTTTEEEEEEDDDDDDDDDDDDDDDD======================//
}
});
module.exports = app;

MEAN stack application - getting details of a single user, querying by username

I have built an API to GET and POST values into a database(MongoDB) using NodeJS and Express.
I am able to get the total list of users stored on my database (localhost:3000/user)
But I want to get a single users details by either entering the userID or userName(localhost:3000/user/:username)(localhost:3000/user/:userID)
I am able to get a single users details through ObjectID(localhost:3000/user/:id)
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');
//Router for developers
var developer = require('./routes/developer');
//Router for TvShows
var tvshow = require('./routes/tvshow');
//Router for TvShows
var user = require('./routes/user');
//Router for TvShowRating
var tvshowrating = require('./routes/tvshowrating');
//Router for TvShowEpisodes
var tvshowepisodes = require('./routes/tvshowepisodes');
//Router for TvShowNewsFeed
var tvshownewsfeed = require('./routes/tvshownewsfeed');
//Router for TvShowSeason
var tvshowseason = require('./routes/tvshowseason');
//Router for TvShowRatingUser
var tvshowratinguser = require('./routes/tvshowratinguser');
// load mongoose package
var mongoose = require('mongoose');
// Use native Node promises
mongoose.Promise = global.Promise;
// connect to MongoDB
//mongoose.connect('<string>')
//mongoose.connect('mongodb://localhost/televisionary-api')
.then(() => console.log('connection succesful'))
.catch((err) => console.error(err));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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')));
//Registering routers
app.use('/developer', developer);
app.use('/tvshow', tvshow);
app.use('/user', user);
app.use('/tvshowrating', tvshowrating)
app.use('/tvshowepisodes', tvshowepisodes)
app.use('/tvshownewsfeed', tvshownewsfeed)
app.use('/tvshowseason', tvshowseason)
app.use('/tvshowratinguser', tvshowratinguser)
// 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;
. routes/User.js
var express = require('express');
var router = express.Router();
var User = require('../models/User.js');
/* GET /user listing. */
router.get('/', function(req, res, next) {
User.find(function (err, user) {
if (err) return next(err);
res.json(user);
});
});
/* POST /user */
router.post('/', function(req, res, next) {
User.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /user/id */
router.get('/:id', function(req, res, next) {
User.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* PUT /user/:id */
router.put('/:id', function(req, res, next) {
User.findByIdAndUpdate(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /user/:id */
router.delete('/:id', function(req, res, next) {
User.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
. models/User.js
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
userId:Number,
userName: String,
userEmail: String,
userPassword: String,
userCreatedDateTime: Date,
userWatchList: [
{
watchListItemId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowAddedDateTime: Date
}
],
userFavouriteList: [
{
favouriteId:Number,
tvShowId: Number,
tvShowFavouritedDateTime: Date
}
],
userRatings: [
{
tvShowUserRatingId:Number,
tvShowId: Number,
tvShowSeasonId: Number,
tvShowEpisodeId: Number,
tvShowRatedDateTime: Date,
tvShowRating: Number,
tvShowUserTags:[String]
}
]
});
module.exports = mongoose.model('User', userSchema);
If you want to get user details by entering username or userid in one service then modify your service with this:
router.get('/:keyword', function(req, res, next){
User.findOne({$or:[{userName: req.params.keyword}{userId:req.params.keyword}]},
function (err, post) {
if (err) return next(err);
res.json(post);
});
});
You can use findOne method to get a specific user from a database.
router.get('/user/:username', function(req, res, next) {
User.findOne({userName: req.params.username}, function(err, user) {
if(err)
console.log(err);
else
//do something with user
})
});
Same for fetching user using userId.

404 when attempting rooting with param on Express

i get 404 error when rooting with param , whereas all other rootings defined on my rootes/users.js file work perfectly , for example i get the desire result when i call :
localhost:3000/users/users .
but get 404 when i call localhost:3000/users/users/12315454 which should correspond to the rooter /users:user_id in my users.js (you can find it below)
var express = require('express');
var router = express.Router();
var User = require('../models/user');
router.route('/users:user_id')
.get(function(req, res) {
console.log("attempting user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
res.json(place);
});
})
.put(function(req, res) {
console.log("attempting to update user");
User.findById(req.params.user_id, function(err, place) {
if (err)
res.send(err);
user.username = req.body.name;
user.visitedPlaces = req.body.visitedPlaces;
user.likedItems = req.body.likedItems;
//user.local.email= req.body.email;
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user updated!' });
});
});
})
.delete(function(req, res) {
User.remove({
_id: req.params.user_id
}, function(err, bear) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
router.route('/users')
// get all the users (accessed at GET http://localhost:8080/api/users)
.get(function(req, res) {
User.find(function(err, places) {
if (err)
res.send(err);
res.json(places);
});
});
router.route('/adduser')
.post(function(req, res) {
var user = new User();
user.password = user.generateHash (req.body.password); // set the users name (comes from the request)
user.username = req.body.username;
console.log(req.body)
console.log("user name :"+req.body.username);
user.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'user created!' });
});
});
module.exports = router;
my app.js config
var express = require('express');
var path = require('path');
var favicon = require('static-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 FacebookStrategy = require('passport-facebook').Strategy;
var mongo = require('mongoskin');
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
var port = process.env.PORT || 3030;
var router = express.Router();
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
//Facebook app credentials
var FACEBOOK_APP_ID = '******09';
var FACEBOOK_APP_SECRET = '9a*******3';
//app secret for dev = 9adfcaa6d7989d8adc12852badcf69f3
// app ifd for dev = 492502667544609
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'app')));
//var routes = require('./routes/index');
require('./config/passport')(passport); // pass passport for configuration
var users = require('./routes/users');
var places = require('./routes/places');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// set up our express application
app.use(logger('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
// required for passport
app.use(session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session());
app.use(favicon());
//app.use(flash()); // use connect-flash for flash messages stored in session
// Make our db accessible to our router WARNING THIS MUST BE PUT before the rooting stuff above
app.use('/api', router);
app.use('/places', places);
app.use('/users', users);
// routes ======================================================================
require('./routes/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.get('/', function(req, res, next) {
res.sendfile('./app/index.html');
});
/// catch 404 and forwarding 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: {}
});
});
// test authentication
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { console.log("is authenticated");
return next(); }
console.log("not authenticated");
res.redirect('/')
}
// launch ======================================================================
console.log('The magic happens on port ' + port)
module.exports = app;
Add a slash in your route, between the users and :user_id:
router.route('/users/:user_id')
^---------here

Resources