我試圖實現在此基礎上回答一個基本的登錄機制: https://stackoverflow.com/a/8003291/5111904快速登錄並重定向使用Node.js的
在我的後端我處理登錄post
要求是這樣的:
app.post('/login', function (req, res) {
console.log(req.body);
if (req.body.user === 'normal' && req.body.password === '12345') {
req.session.user_id = 0; // This is failing (req.session is undefined)
res.redirect('/index');
} else {
res.send('Bad user/pass');
}
});
服務器正在使用https
:
server = https.createServer(https_options, app).listen(PORT, HOST);
當第E客戶機點擊登錄按鈕是越來越執行該代碼:
function postLogin(){
var url = "/login";
var xhr = new XMLHttpRequest();
var data = {
user: userInput.value,
password: passwordInput.value
};
xhr.open("POST", url, true);
xhr.onreadystatechange = function (oEvent) {
if(xhr.readyState === 4){
// Checking status codes
if(xhr.status === 200){
onSuccess(xhr.responseText, xhr.responseType);
}
else{
console.log(xhr.status);
onError();
}
}
}
xhr.setRequestHeader("Content-type", "application/json; charset=UTF-8");
console.log("Sending this data: " + JSON.stringify(data));
xhr.send(JSON.stringify(data));
}
登錄用戶應重定向到索引頁面後:
app.get('/index', (request, response) => {
response.render('main', {});
})
所以我得到了這個問題:
- 在第一個代碼段中,req.session未定義
- 在secod片段中,(xhr.responseText)的值計算爲html的 索引頁面(用戶應該被重定向)
- 如何以正確的方式將用戶重定向到索引頁面?
將只有一個有效的用戶,所以這個代碼不打算被許多人使用,它應該只提供一個基本的安全類型。
你有沒有進口'快車session',如:'導入會話從「快車session'' –
@AnushShrestha我沒有 - 我想這應該解決'undefined'問題 - 將嘗試 - TY –
@AnushShrestha我安裝了軟件包,並像這樣包含它:'const session = require('express-session')' - 仍然有未定義的問題 –