我在使用Express构建的网站上遇到了麻烦。
这是它应该如何工作的:
我的问题是,当我在POST /登录路由中调用res.render()时,配置文件页面未呈现,我不确定原因,因为控制台在res之前立即记录日志。 render()正常工作,表明已发出AJAX请求。
以下是服务器路由:
//homepage
app.get("/", (req, res) => {
res.render("home.hbs");
});
//signup
app.post("/signup", urlencodedParser, (req, res, next) => {
let body = _.pick(req.body, ['studentid', 'name', 'password', 'department']);
let user = new User(body);
user.save().then(() => {
return user.generateAuthToken();
}).then((token) => {
res.header({'x-auth': token, studentid: req.body.studentid}).send(user);
}).catch((err) => {
res.status(400).send(err);
})
})
//go to profile
app.post("/loggedin", authenticate, (req, res) => {
console.log(`token: ${req.header('x-auth')}`)
console.log(`name from database: ${req.user.name}`)
res.render(`loggedIn.hbs`);
})
这是当用户提交表单时触发的前端javascript:
$.ajax({
url: "/signup",
method: "POST",
data: {
name: name,
studentid: studentid,
department: department,
password: password,
},
success: function (response, textStatus, xhr) {
let auth = xhr.getResponseHeader('x-auth');
let id = xhr.getResponseHeader('studentid');
localStorage.setItem('x-auth', auth);
localStorage.setItem('studentid', id);
// redirect to loggedin pages
$.ajax({
url: "/loggedin",
type: "POST",
beforeSend: function(xhr){xhr.setRequestHeader('x-auth', auth);}, // send token with request
success: function(page) {
console.log('redirecting');
},
fail: function() {
alert('Cannot log in, please try again later')
}
});
},
error: function (response, textStatus, xhr) {
if(response.status == 400) {
if(response.responseJSON.errmsg && response.responseJSON.errmsg.includes("E11000 duplicate key error collection")) {
return alert("There is already a user with the same student id in the database.")
}
alert("Sign up failed, please try again later.")
}
}
});
任何建议将不胜感激