node.js - Chaining Express.js 4's res.status(401) to a redirect -
node.js - Chaining Express.js 4's res.status(401) to a redirect -
i'd send response code of 401 if requesting user not authenticated, i'd redirect when request html request. i've been finding express 4 doesn't allow this:
res.status(401).redirect('/login') does know of way handle this? might not limitation of express, since i'm asking pass 2 headers, don't see why should case. should able pass "not authenticated" response , redirect user in 1 go.
there subtle diferences methods sending new location header.
with redirect:
app.get('/foobar', function (req, res) { res.redirect(401, '/foo'); }); // responds http/1.1 401 unauthorized x-powered-by: express location: /foo vary: take content-type: text/plain; charset=utf-8 content-length: 33 date: tue, 07 apr 2015 01:25:17 gmt connection: keep-alive unauthorized. redirecting /foo with status , location:
app.get('/foobar', function (req, res) { res.status(401).location('/foo').end(); }); // responds 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 original (incorrect) approach using redirect:
app.get('/foobar', function (req, res) { res.status(401).redirect('/foo')(); }); // responds http/1.1 302 moved temporarily x-powered-by: express location: /foo vary: take 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 /foo so looks redirect abandon previous status codes , send default value (unless specified within method call). makes sense due utilize of middleware within express. if had global middleware doing pre-checks on requests (like checking right accepts headers, etc.) wouldn't know redirect request. authentication middleware , know override previous settings set them correctly.
update: stated in comments below though express can send 4xx status code location header not mean acceptable response request client understand according specs. in fact ignore location header unless status code 3xx value.
node.js redirect express http-status-code-401
Comments
Post a Comment