Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass headers while doing res.redirect in express js

Tags:

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?

like image 978
nikhil.g777 Avatar asked Oct 12 '16 11:10

nikhil.g777


People also ask

Can't set headers after they are sent Res redirect?

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.

How use redirect in Express JS?

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.

What is difference between RES redirect and res render?

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.

Are express headers case sensitive?

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.


1 Answers

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'); }); 
like image 189
Stavros Zavrakas Avatar answered Sep 18 '22 11:09

Stavros Zavrakas