我试图实现在此基础上回答一个基本的登录机制: 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')' - 仍然有未定义的问题 –