Node js passport redirect results in 404

Adamater Source

I am making a post request to /login with my email and password, passport authenticates it correctly, error isn't called, and then return res.redirect('/profile') gets run too. But it returns 404.

These are the two login functions I tried, both of them result in "GET /profile 404", even though when I do "GET /profile" normally it returns 200

//     router.post('/login', passport.authenticate('local-login', {
//       successRedirect : '/profile', // redirect to the secure profile section
//       failureRedirect : '/login' // redirect back to the signup page if there is an error
//     }));

router.post('/login', function(req, res, next) {
  passport.authenticate('local-login', function(err, user) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      console.log("thisgetsrun")
      return res.redirect('/profile');
    });
  })(req, res, next);
});

here is /profile

router.get('/profile', isLoggedIn, function(req, res) {
    console.log("profile")
    res.render('profile');
});

and isLoggedIn

function isLoggedIn(req, res, next) {
    console.log("is logged in")
    if (req.isAuthenticated())
        return next();
    res.redirect('/');
}

neither the console log in isloggedin or profile are printed

and finally my 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 passport = require('passport');
require('./config/passport')(passport)
var mongo = require('mongodb');
var monk = require('monk');
var db = monk("mongodb.........");
var routes = require('./routes/index');
var users = require('./routes/users');

var session = require('express-session');
var app = express();

 ....

app.use(function(req,res,next){
    req.db = db;
    next();
});

app.use(session({ secret: 'blah' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions

app.use('/', routes);
app.use('/users', users);

app.use(function(err, req, res, next) {
  res.status(404);
  res.render('404');
});

module.exports = app;

Does anyone know why this is happening?

javascriptnode.jspassport.jspassport-local

Answers

answered 2 years ago leobelizquierdo #1

Are you sure that the view profile exists and is located properly with respect to the view engine? When you do "GET /profile" normally isLoggedIn redirect to '/' because req.isAuthenticated() is false, so the problem is when the user gets log in and res.render('profile'); is called. Make sure that you have an view engine setup similar to this:

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

and the profile view is inside the views folder.

comments powered by Disqus