我正在研究一個應用程序,它有服務器上的node.js和mongodb,前端的db和Backbone.js。我正在開發用戶登錄,所以我使用了passport.js庫。我的登錄'post'方法有問題:它不會重定向到另一個頁面(它是SPA,所以我的意思是渲染Backbone視圖)。下面的代碼:登錄驗證後快速重定向
//standard express setup...
app.post('/api/auth', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
req.session.messages = [info.message];
return res.redirect('/')
}
req.logIn(user, function(err) {
if (err) {
return next(err);
} else {
console.log('yup, working'); //Can see the response in the console
return res.redirect('/api');
}
});
})(req, res, next);
});
app.get('/api', function (request, response) {
response.send('Login successful!');
});
所以我能看到的console.log消息罰款,對路線的GET請求被觸發......但沒有實際發生。所以我想我已經誤解了'res.redirect'是如何工作的 - 我想在登錄成功後導航到那條路線。我想過使用window.location,但這是一個很好的長期解決方案嗎?我沒有在服務器上使用任何html模板,所以我不能(我不認爲)做'res.render('index')'這樣簡單的事情'
什麼是最好的方式來接近這個?提前致謝。
你可以用簡單的方法解決這個問題,只需使用'window.href'或不使用'res.redirect',而是發送一些客戶端期望的json,以便繼續前進無論應該做什麼。 如果可能的話,保留單個骨幹模型用戶並監視該模型的狀態,然後讓所有其他模型監聽用戶模型並採取行動。 – Gntem