填写登录凭据后,我正在尝试登录到我的个人资料页面,但我被重定向到 http://localhost:3000/myprofile%20,出现 404 错误。
这是我的代码的样子
登录路线
router.post('/login', function(req, res, next){
if(req.body.email && req.body.password ){
Reg.authenticate(req.body.email, req.body.password, function(error, user){
if(error || !user){
var err = new Error("Wrong email or password");
err.status = 401;
return next(err);
}
else{
req.session.userId = user._id;
return res.redirect('/myprofile ')
}
});
}else{
var err = new Error("Email and Password required");
err.status = 401;
return next(err);
}
});
获取/个人资料
router.get('/myprofile', function(req, res, next){
if(!req.session.userId){
var err = new Error("Please login with your email and password");
err.status = 403;
return next(err);
}
Reg.findById(req.session.userId)
.exec(function(error, user){
if(error){
return next(error);
}else{
return res.render('myprofile',{title:'My Profile', name:user.name, email:user.email, hobbies:user.hobbies,
address:user.address, medicalhistory:user.medicalhistory, allergies:user.allergies, gender:user.gender, bloodgroup:user.bloodgroup,
birthdate:user.birthdate, country:user.country, mobileNumber:user.mobileNumber})
}
})
});
代码中有一个额外的空格:
else {
req.session.userId = user._id;
return res.redirect('/myprofile ')
// ^
}
删除它,您将被重定向到正确的路线:
router.post('/login', function(req, res, next) {
if (req.body.email && req.body.password) {
Reg.authenticate(req.body.email, req.body.password, function(error, user) {
if (error || !user) {
var err = new Error("Wrong email or password");
err.status = 401;
return next(err);
} else {
req.session.userId = user._id;
return res.redirect('/myprofile')
}
});
} else {
var err = new Error("Email and Password required");
err.status = 401;
return next(err);
}
});
在 else 部分中,您将一个空格 ( ( 附加到重定向函数
else{
req.session.userId = user._id;
return res.redirect('/myprofile ') // this line
}
%20
是">"空间的 urlencode 字符。您可能知道
0x20
是">的ASCII,
return res.redirect('/myprofile ')
是return res.redirect('/myprofile')
的十六进制。
在你的返回(在你的其他条件下(有一个空格 ->CC_7它应该是这样的 -> CC_8