ExpressJS:res.redirect()不能按预期工作? [英] ExpressJS : res.redirect() not working as expected?

查看:539
本文介绍了ExpressJS:res.redirect()不能按预期工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为此奋斗2天,尽可能地谷歌和堆栈,但我无法解决问题。

I've been struggling for 2 days on this one, googled and stackoverflowed all I could, but I can't work it out.

我正在建设一个简单的节点应用程序(+ Express + Mongoose),具有重定向到主页的登录页面。这是我的服务器咖啡代码:

I'm building a simple node app (+Express + Mongoose) with a login page that redirects to the home page. Here's my server Coffee code :

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 '/'

登录页面向/ credentials发出POST请求,其中发布的数据已被验证。这个工作。我可以在Node控制台中看到这里我们是:'/ credentials'。

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.

然后出现问题:res.redirect无法正常工作。我知道它确实达到'/'路由,因为:

Then comes the issue : the res.redirect doesn't work properly. I know that it does reach the '/' route, because :


  1. 我可以在Node控制台中看到这里我们是:root

  2. 将index.html页面作为响应发送回浏览器,但不会显示在窗口中。
    Chrome检查器显示POST请求响应,我可以看到发送到检查器中的浏览器的HTML代码,但是URL保持/登录,登录页面仍然显示在屏幕上。

  1. I can see "Here we are : root" in the Node console
  2. 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.

(编辑)重定向是在Mongoose的回调函数中,它不是同步的(NodeJS应该是)。我刚刚删除了Mongoose验证内容。

(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.

我尝试添加 res.end() t工作

我尝试过

req.method = 'get'; 
res.redirect('/');

res.writeHead(302, {location: '/'});
res.end();

不工作

什么是我做错了吗如何真正离开'/登录'页面,将浏览器重定向到'/'并显示收到的HTML代码?

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?

感谢一百万的帮助提前:)

Thanks a million for your help in advance :)

推荐答案

在您的get / route中添加以下内容:

Add the following in your get / route :

  res.setHeader("Content-Type", "text/html")

您的浏览器将呈现文件而不是下载

Your browser will render file instead of downloading it

这篇关于ExpressJS:res.redirect()不能按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆