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

//'/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
//     }));'/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); }
      return res.redirect('/profile');
  })(req, res, next);

here is /profile

router.get('/profile', isLoggedIn, function(req, res) {

and isLoggedIn

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

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');
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();


    req.db = db;

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

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

app.use(function(err, req, res, next) {

module.exports = app;

Does anyone know why this is happening?



answered 3 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