node.js ExpressJS:res.redirect() 没有按预期工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27202075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ExpressJS : res.redirect() not working as expected?
提问by Jeremy Thille
I've been struggling for 2 days on this one, googled and stackoverflowed all I could, but I can't work it out.
我已经在这个问题上苦苦挣扎了 2 天,尽我所能在谷歌上搜索和计算,但我无法解决。
I'm building a simple node app (+Express + Mongoose) with a login page that redirects to the home page. Here's my server JS code :
我正在构建一个简单的节点应用程序(+Express + Mongoose),其登录页面重定向到主页。这是我的服务器 JS 代码:
app
.get('/', (req, res) => {
console.log("Here we are : root");
return res.sendfile(__dirname + '/index.html');
})
.get('/login', (req, res) => {
console.log("Here we are : '/login'");
return res.sendfile(__dirname + '/login.html');
})
.post('/credentials', (req, res) => {
console.log("Here we are : '/credentials'");
// Some Mongoose / DB validations
return res.redirect('/');
});
The login page makes a POST request to /credentials, where posted data is verified. This works. I can see "Here we are : '/credentials'" in the Node console.
登录页面向 发出 POST 请求/credentials,在此验证已发布的数据。这有效。我可以在 Node 控制台中看到“Here we are : '/credentials'”。
Then comes the issue : the res.redirect doesn't work properly. I know that it does reach the '/' route, because :
然后是问题: res.redirect 不能正常工作。我知道它确实到达了“/”路线,因为:
- I can see "Here we are : root" in the Node console
- The index.html page is being sent back to the browser as a reponse, but not displayed in the window. Chrome inspector shows the POST request response, I CAN see the HTML code being sent to the browser in the inspector, but the URL remains /login and the login page is still being displayed on screen.
- 我可以在 Node 控制台中看到“Here we are : root”
- index.html 页面作为响应被发送回浏览器,但未显示在窗口中。Chrome 检查器显示 POST 请求响应,我可以在检查器中看到发送到浏览器的 HTML 代码,但 URL 仍然是 /login 并且登录页面仍在屏幕上显示。
(Edit) The redirection is in Mongoose's callback function, it's not synchronous (as NodeJS should be). I have just removed Mongoose validation stuff for clarity.
(编辑)重定向在 Mongoose 的回调函数中,它不是同步的(NodeJS 应该如此)。为了清楚起见,我刚刚删除了 Mongoose 验证内容。
I have tried adding res.end(), doesn't work
我试过添加res.end(),不起作用
I have tried
我试过了
req.method = 'get';
res.redirect('/');
and
和
res.writeHead(302, {location: '/'});
res.end();
Doesn't work
不起作用
What am I doing wrong? How can I actually leave the '/login' page, redirect the browser to '/' and display the HTML code that it received?
我究竟做错了什么?我怎样才能真正离开“/登录”页面,将浏览器重定向到“/”并显示它收到的 HTML 代码?
Thanks a million for your help in advance :)
提前感谢一百万您的帮助:)
回答by Kelrynn
The problem might not lie with the backend, but with the frontend. If you are using AJAX to send the POST request, it is specifically designed to not change your url.
问题可能不在于后端,而在于前端。如果您使用 AJAX 发送 POST 请求,它是专门为不更改您的 url 设计的。
Use window.location.hrefafter AJAX's request has completed (in the .done()) to update the URL with the desired path, or use JQuery: $('body').replaceWith(data)when you receive the HTML back from the request.
使用window.location.hrefAJAX的请求后,已经完成(在.done())与所需的路径更新URL,或使用JQuery:$('body').replaceWith(data)当您收到请求的HTML回来。
回答by Matthew Bakaitis
It's almost certain that you are making an async call to check Mongoose but you haven't structured the code so that the redirect only happens after the async call returns a result.
几乎可以肯定,您正在进行异步调用来检查 Mongoose,但您还没有构造代码,因此重定向仅在异步调用返回结果后发生。
In javascript, the POSTwould look like something this:
在 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('/');
};
};
You can also see questions like Async call in node.js vs. mongoosefor parallel/related problems...
您还可以在 node.js 与 mongoose 中看到诸如异步调用之类的问题,以解决并行/相关问题...
回答by Daphoque
Add the following in your get / route :
在您的 get / route 中添加以下内容:
res.setHeader("Content-Type", "text/html")
Your browser will render file instead of downloading it
您的浏览器将呈现文件而不是下载文件
回答by nicer00ster
I've been working on implementing nodemailer into my NextJS app with Express. Was having this issue and came across this. I had event.preventDefault() in my function that was firing the form to submit and that was preventing the redirect as well, I took it off and it was redirecting accordingly.
我一直致力于使用 Express 在我的 NextJS 应用程序中实现 nodemailer。遇到了这个问题并遇到了这个。我的函数中有 event.preventDefault() 触发表单提交,这也阻止了重定向,我将其取下并相应地重定向。
回答by user13074009
If you are using an asynchronous request to backend and then redirecting in backend, it will redirect in backend(ie. it will create a new get request to that url). but won't change url in front end To make it work: 1. use windows.location.href = "/url" 2. change your async request(in frontent) to simple anchor tag ()
如果您对后端使用异步请求,然后在后端重定向,它将在后端重定向(即,它将创建一个到该 url 的新 get 请求)。但不会在前端更改 url 要使其工作: 1. 使用 windows.location.href = "/url" 2. 将异步请求(在前端)更改为简单的锚标记()

