Jer*_*lle 22 redirect node.js express
我已经在这个问题上苦苦挣扎了2天,用Google搜索并尽可能地堆叠,但是我无法解决这个问题.
我正在构建一个简单的节点应用程序(+ Express + Mongoose),其中包含一个重定向到主页的登录页面.这是我的服务器咖啡代码:
app
.get '/', (req, res) ->
console.log "Here we are : root"
res.sendfile(__dirname + '/index.html')
.get '/login', (req, res) ->
console.log "Here we are : '/login'"
res.sendfile(__dirname + '/login.html')
.post '/credentials', (req, res) ->
console.log "Here we are : '/credentials'"
# (here comes credentials validation stuff with Mongoose)
res.redirect '/'
Run Code Online (Sandbox Code Playgroud)
登录页面向/凭证发出POST请求,其中验证发布的数据.这有效.我可以在Node控制台中看到"Here we are:'/ credentials'".
然后是问题:res.redirect无法正常工作.我知道它确实达到'/'路线,因为:
(编辑)重定向是在Mongoose的回调函数中,它不是同步的(因为NodeJS应该是).为清楚起见,我刚刚删除了Mongoose验证内容.
我试过添加res.end(),不起作用
我试过了
req.method = 'get';
res.redirect('/');
Run Code Online (Sandbox Code Playgroud)
和
res.writeHead(302, {location: '/'});
res.end();
Run Code Online (Sandbox Code Playgroud)
不行
我究竟做错了什么?我怎样才能真正离开'/ login'页面,将浏览器重定向到'/'并显示它收到的HTML代码?
万分感谢您的帮助:)
Kel*_*ynn 25
问题可能不在于后端,而在于前端.如果您使用AJAX发送POST请求,则专门设计为不更改您的URL.
使用window.location.hrefAJAX请求完成后(在.done())与所需的路径更新URL,或使用JQuery:$('body').replaceWith(data)当您收到HTML从请求回来.
小智 6
如果您使用异步请求到后端,然后在后端重定向,它将在后端重定向(即它将创建一个到该 URL 的新 get 请求),但不会更改前端的 URL。
为了使其发挥作用,您需要:
window.location.href = "/url"<a></a>)