ExpressJS:res.redirect()不能按预期工作?
我一直在这个问题上挣扎了两天,尽可能地用google和stackoverflow,但是我无法解决这个问题。
我正在构build一个简单的节点应用程序(+ Express + Mongoose),其中包含一个redirect到主页的login页面。 这是我的服务器咖啡代码:
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 '/'
login页面向/ credentials发送POST请求,其中发布的数据经过validation。 这工作。 我可以在节点控制台中看到“我们在这里:'/ credentials'”。
然后出现问题:res.redirect不能正常工作。 我知道它确实到达了“/”路线,因为:
- 我可以在节点控制台中看到“我们是:root”
- index.html页面将作为响应发送回浏览器,但不会显示在窗口中。 Chrome检查器显示POST请求响应,我可以看到HTML代码发送到检查器中的浏览器,但URL保持/login,login页面仍然显示在屏幕上。
(编辑)redirect是在Mongoose的callback函数中,它不是同步的(如NodeJS应该)。 我刚刚清除了Mongoosevalidation的东西。
我曾尝试添加res.end()
,不起作用
我努力了
req.method = 'get'; res.redirect('/');
和
res.writeHead(302, {location: '/'}); res.end();
不起作用
我究竟做错了什么? 我怎么才能离开“/login”页面,将浏览器redirect到“/”并显示它收到的HTML代码?
非常感谢你的帮助提前:)
问题可能不在于后端,而是在前端。 如果您使用AJAX发送POST请求,它是专门devise,不会更改您的url。
在AJAX请求完成之后(在.done()
)使用window.location.href
来更新具有所需path的URL,或者使用JQuery: $('body').replaceWith(data)
请求。
几乎可以肯定,你正在做一个asynchronous调用来检查Mongoose,但是你没有构造代码,所以redirect只发生在asynchronous调用返回结果之后。
在JavaScript中, POST
看起来像这样:
function validateCredentials(user, callback){ // takes whatever you need to validate the visitor as `user` // uses the `callback` when the results return from Mongoose } app.post('/credentials', function(req, res){ console.log("Here was are: '/credentials'"; validateCredentials(userdata, function(err, data){ if (err) { // handle error and redirect to credentials, // display an error page, or whatever you want to do here... } // if no error, redirect res.redirect('/'); }; };
你也可以看到像在asynchronous调用node.js与mongoose并行/相关问题的问题…
在你的get / route中添加以下内容:
res.setHeader("Content-Type", "text/html")
您的浏览器将呈现文件,而不是下载它