简体   繁体   中英

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

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?

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');
});

As people have asked if there was any workaround about the fact headers are not properly set after a redirect, there is actually two ways you can work with:

First, by using a query parameter in the redirect url, which you could be extracted client-side. You could even remove it on load from the url using the history API, like showed here .

history.pushState(null, '', location.href.split('?')[0])

Another solution would be to set a cookie before the redirect, and getting it in the client. Personally I prefer that in the sense it doesn't pollute my url in any way, I just need to remove this cookie on load with a simple helper:

export const removeCookie = name => {
  document.cookie = `${name}=; Max-Age=0`
}

It is not a Express or any backend limitation, is just the way that browsers works, Express just responds with a Redirect header and the browser implements the redirection, if you are redirecting to the same domain then you got all headers, cookies and the original payload.

But if you are redirecting to another domain, the browser rip off the headers for security reasons and is nothing that you can do about it, so if you really need to do it, you will need to consume the external service with your own service in the backend, nothing with Redirect Header because this depends of the browser implementation.

I haven't tried this solution myself, but I think it worth the shot.

res.location(REDIRECT_URL)
res.set(HEADERS)

res.stats(302).end()

I hope it helps, Abel

Why cant you try the axios library

    npm install axios

and then

    return new Promise((resolve, reject) => {

        axios({
            "headers" : {
                "content-type" : "application/vnd.api+json"
            },
            "method" : method,
            "url" : url,
            "data" : data
        }).then((ax_res) => {
            var obj = {
                "status" : ax_res.status,
                "data" : ax_res.data
            }
            resolve(obj)
            return(obj)
        }).catch((ax_res) => {
            var obj = {
                "status" : ax_res.response.status,
                "data" : ax_res.response.data
            }
            resolve(obj)
            return(obj)
        })

    })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM