Chaining Express.js 4's res.status(401) to a redirect

后端 未结 3 2034
长发绾君心
长发绾君心 2020-12-14 20:00

I\'d like to send a response code of 401 if the requesting user is not authenticated, but I\'d also like to redirect when the request was an HTML request. I\'ve been finding

3条回答
  •  抹茶落季
    2020-12-14 20:45

    There are some subtle diferences with the methods for sending back a new location header.

    With redirect:

    app.get('/foobar', function (req, res) {
      res.redirect(401, '/foo');
    });
    // Responds with
    HTTP/1.1 401 Unauthorized
    X-Powered-By: Express
    Location: /foo
    Vary: Accept
    Content-Type: text/plain; charset=utf-8
    Content-Length: 33
    Date: Tue, 07 Apr 2015 01:25:17 GMT
    Connection: keep-alive
    
    Unauthorized. Redirecting to /foo
    

    With status and location:

    app.get('/foobar', function (req, res) {
      res.status(401).location('/foo').end();
    });
    // Responds with
    HTTP/1.1 401 Unauthorized
    X-Powered-By: Express
    Location: /foo
    Date: Tue, 07 Apr 2015 01:30:45 GMT
    Connection: keep-alive
    Transfer-Encoding: chunked
    

    With the original (incorrect) approach using redirect:

    app.get('/foobar', function (req, res) {
      res.status(401).redirect('/foo')();
    });
    // Responds with 
    HTTP/1.1 302 Moved Temporarily
    X-Powered-By: Express
    Location: /foo
    Vary: Accept
    Content-Type: text/plain; charset=utf-8
    Content-Length: 38
    Date: Tue, 07 Apr 2015 01:26:38 GMT
    Connection: keep-alive
    
    Moved Temporarily. Redirecting to /foo
    

    So it looks like redirect will abandon any previous status codes and send the default value (unless specified inside the method call). This makes sense due to the use of middleware within Express. If you had some global middleware doing pre-checks on all requests (like checking for the correct accepts headers, etc.) they wouldn't know to redirect a request. However the authentication middleware would and thus it would know to override any previous settings to set them correctly.

    UPDATE: As stated in the comments below that even though Express can send a 4XX status code with a Location header does not mean it is an acceptable response for a request client to understand according to the specs. In fact most will ignore the Location header unless the status code is a 3XX value.

提交回复
热议问题