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)};
我該如何擺脫這個錯誤?
謝謝。
你能在你的/用戶配置文件路徑使用req.user而不是傳遞呢? –
@GibryonBhojraj謝謝你的回覆。我在**問題的**編輯**部分添加了一些編輯。我可以將用戶名添加到請求中,但是它返回了我在** EDIT **部分中陳述的錯誤。這種情況僅在有時候發生。有時會起作用,但有時會出現該錯誤。 – dasunpubudumal