2017-11-04 301 views
1

我使用Express和Passport制作了一个小型登录应用程序。但似乎我不能将用户导入特定的用户配置文件。发生的事情是,用户填写一个HTML表单,并且他必须重定向到他自己的配置文件页面(为了简单起见,可以说这个页面与其他用户页面仅在标题方面有所不同)。我有这在我的用户路线。 (即routes/users.js)使用Passport在Express中传递参数

router.get('/userprofile', authenticationMiddleware(), function (req, 
res, next) { 
    res.render('userprofile'); 
}); 


router.post('/login', passport.authenticate('local-login', { 
     successRedirect: '/users/userprofile', 
     failureRedirect: '/users/login', 
     failureFlash: true 
})); 

在我的passport.js配置文件中,我有这个。

passport.use('local-login', new LocalStrategy({ 
    usernameField: 'username', 
    passwordField: 'password', 
    passReqToCallback: true 
}, function (req, username, password, done) { 
    db.pool.getConnection(function (err, connection) { 
     if(err) throw err; 
     var query = connection.query('SELECT * from users WHERE username = ?', username, function (err, rows) { 
      if(err) return done(err); 
      if(!rows.length) { 
       return done(null, false, req.flash('loginMessage', 'No User Found')); 
      } 
      //Comparing passwords using bcrypt 
      bcrypt.compare(password, rows[0].password, function(error, res){ 
       if(res){ 
        return done(null, rows[0]); 
       } else { 
        return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); 
       } 
      }); 
     }); 
    }); 
})); 

我需要做的就是从表单的用户名,并把它传递到passport.authenticate的successRedirect属性,然后我可以修改get方法添加一个类似“/用户/路由参数:用户名'并呈现'用户名'视图。

我该怎么做?

编辑:

我做了这样的事情。

router.get('/userprofile/:username', authenticationMiddleware(), function (req, res, next) { 
    res.render('userprofile', { 
     username: req.params.username, 
     title: 'Welcome, '+ req.params.username 
    }); 
}); 


router.post('/login', function (req, res, next) { //Testing callback. 
    console.log("Username is: " + req.body.username); 
    passport.authenticate('local-login', { 
     successRedirect: '/users/userprofile/' + req.body.username, 
     failureRedirect: '/users/login', 
     failureFlash: true 
    })(req, res);  
    next(); 
}); 

这对一些尝试有效。但是,它有时会返回此错误。

POST /users/login 404 43.741 ms - 5226 /home/dasun/WebstormProjects/schoolentry/node_modules/passport/lib/middleware/authenticate.js:249 
     if (err) { return next(err)}; 

我该如何摆脱这个错误?

谢谢。

+0

你能在你的/用户配置文件路径使用req.user而不是传递呢? –

+0

@GibryonBhojraj谢谢你的回复。我在**问题的**编辑**部分添加了一些编辑。我可以将用户名添加到请求中,但是它返回了我在** EDIT **部分中陈述的错误。这种情况仅在有时候发生。有时会起作用,但有时会出现该错误。 – dasunpubudumal

回答

0

找到了答案。我在/login路线中错过了POST方法中的next

即我应该写

router.post('/login', function (req, res, next) { //Testing callback. 
console.log("Username is: " + req.body.username); 
passport.authenticate('local-login', { 
    successRedirect: '/users/userprofile/' + req.body.username, 
    failureRedirect: '/users/login', 
    failureFlash: true 
})(req, res, next); 
});