I am working on express js and I need to redirect to a page which needs authentication. This is my code:
router.get('/ren', function(req, res) { var username = 'nik', password = 'abc123', auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64'); res.redirect('http://localhost:3000/api/oauth2/authorize'); })
How can I set headers to this redirect command?
The "Cannot set headers after they are sent to the client" error occurs when the server in an express. js application sends more than one response for a single request, e.g. calling res. json() twice. To solve the error, make sure to only send a single response for each request.
The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.
In the specific case you show in your question, when you "approve" the login, you may then want to do a res. redirect() to whatever URL you want the user to start on after the login and then create a route for that URL which you will use res. render() to render that page.
2 Answers. Show activity on this post. The problem arises because in the HTTP protocol, headers are case-insensitive. This means that content-type , Content-Type , and coNTEnt-tYPe all refer to the same header, and the Express framework needs to be able to handle any of them.
Doesn't express forward the headers automatically if you redirect with 301 (Moved Permanently) or 302 (Found)?
If not, this is how you can set headers:
res.set({ 'Authorization': auth })
or
res.header('Authorization', auth)
and then call the
res.redirect('http://localhost:3000/api/oauth2/authorize');
Finally, something like that should work:
router.get('/ren', function(req, res) { var username = 'nik', password = 'abc123', auth = "Basic " + new Buffer(username + ":" + password).toString("base64"); res.header('Authorization', auth); res.redirect('http://localhost:3000/api/oauth2/authorize'); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With