Why doesn't express redirect properly when I e

2019-05-24 03:57发布

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条回答
一夜七次
2楼-- · 2019-05-24 04:47

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.

查看更多
登录 后发表回答