发送新位置标头的方法存在一些细微的差异。
与
redirect:
app.get('/foobar', function (req, res) { res.redirect(401, '/foo');});// Responds withHTTP/1.1 401 UnauthorizedX-Powered-By: ExpressLocation: /fooVary: AcceptContent-Type: text/plain; charset=utf-8Content-Length: 33Date: Tue, 07 Apr 2015 01:25:17 GMTConnection: keep-aliveUnauthorized. Redirecting to /foo与
status和
location:
app.get('/foobar', function (req, res) { res.status(401).location('/foo').end();});// Responds withHTTP/1.1 401 UnauthorizedX-Powered-By: ExpressLocation: /fooDate: Tue, 07 Apr 2015 01:30:45 GMTConnection: keep-aliveTransfer-Encoding: chunked与原始(不正确)方法一起使用
redirect:
app.get('/foobar', function (req, res) { res.status(401).redirect('/foo')();});// Responds with HTTP/1.1 302 Moved TemporarilyX-Powered-By: ExpressLocation: /fooVary: AcceptContent-Type: text/plain; charset=utf-8Content-Length: 38Date: Tue, 07 Apr 2015 01:26:38 GMTConnection: keep-aliveMoved Temporarily. Redirecting to /foo因此,看起来
redirect将放弃任何先前的状态代码并发送默认值(除非在方法调用中指定)。由于在Express中使用了中间件,因此很有意义。如果您有一些全局中间件对所有请求进行预检查(例如检查正确的接受标头等),它们将不知道如何重定向请求。但是,身份验证中间件将因此并且将知道可以覆盖任何先前的设置以正确设置它们。
更新:如下面的评论所述,即使Express可以发送带有Location标头的4XX状态代码,也不表示对于请求客户端根据规范理解,这是可接受的响应。实际上,除非状态代码是3XX值,否则大多数都会忽略Location标头。



