Why doesn't express redirect properly when I edit the status code

断了今生、忘了曾经 提交于 2020-01-13 20:42:13

问题


The standard res.redirect('/some/path'); behaves as expected and immediately redirects the request to /some/path, but if I add a status code, e.g., res.redirect(401, '/some/path') and I navigate to the redirecting page, express doesn't redirect to /some/path, instead I just get the following page:

<p>Unauthorized. Redirecting to <a href="/some/path">/</a></p>

and it never redirects. This is the same for any status code I supply just by the way.

Why doesn't a code specified redirect work as I'm expecting it to and how can I return a custom status code and redirect to a different path?


回答1:


The behavior of the Location header, which is used to to redirect someone, is only defined for status codes in the 3xx range, and for 201/202 statuses. Since you are setting the status code to 401, it is ignoring the header and just rendering the response content. It just happens that Express includes some nice text explaining that the user is being redirected in case the redirect is slow.

Also, given the definition of the 401 status code, you are likely misusing it. The 401 code is to let the client know that it needs to send additional authentication information with a give request, e.g. http://en.wikipedia.org/wiki/Basic_access_authentication, so you should not be redirecting to another URL.



来源:https://stackoverflow.com/questions/21519094/why-doesnt-express-redirect-properly-when-i-edit-the-status-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!