快速重定向不会更改req.url [英] Express redirecting doesn't change req.url
问题描述
我有一条成功登录后会重定向的路由
I have a route that redirects upon successful login
app.post('/login', function(req, res){
if(req.body.password === Server.cfg.auth.userPass) {
req.session.user = {nick: req.body.username, pass: req.body.password}
res.redirect('/chat')
} else {
res.render('user/login', { locals: { error: 'Invalid password' } })
}
})
当页面被正确呈现的玉文件刷新时,重定向似乎起作用.但是,URL仍然显示/login,而我的pageTitle变量(通过模板vars设置)也没有改变.如果我在重定向后刷新页面,则所有内容都会更改为原来的样子.只是在重定向之后,它才能保持不变.
The redirect seems to work as the page is refreshed with the correctly rendered jade file. However, the url still says /login and my pageTitle variable (being set through template vars) does not change either. If I refresh the page after the redirect, everything changes to the way it should be. It is only after the redirect that it does not change.
推荐答案
对于那些试图处理来自服务器控制的开发背景的Ajax重定向的人来说,这是很常见的混淆.我的示例显示了授权失败会发生的情况,略有不同.但是您可以使用拦截响应和检查状态等相同的概念,并让客户端JavaScript进行重定向.
This has got to be a pretty common mix up for folks trying to deal with ajax redirects coming from a server controlled development background. My example shows what happens if authorization fails, slightly different; but you can use the same concept of intercepting the response and checking status, etc., and let the client JavaScript do the redirect.
我的客户代码实际上是一个骨干模型,但是依次调用了jquery的ajax:
My client code is actually a backbone model but in turn is calling jquery's ajax like:
model.save({ error:function...
服务器
function requiresLogin(req, res, next) {
if(req.session.user) {
next();
} else {
//res.redirect('/sessions/new?redir=' + req.url); // won't work
res.send("Unauthorized", 403); // send 403 http status
}
}
客户
// Assumes you can get http status from response
error: function(resp, status, xhr)...
if(resp.status === 403) {
window.location = '/sessions/new'; // optionally put a redirLastPage=somewhere
}
这对我来说很理想.我还建议使用谷歌搜索ajax帖子重定向,以了解为什么
This works as desired for me. I'd also suggest googling ajax post redirects to see why this
这篇关于快速重定向不会更改req.url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!