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`
}
链接地址: http://www.djcxy.com/p/36690.html

上一篇: 我如何打开我的jQuery模态与我的元素一样宽,但没有更宽?

下一篇: 如何在express js中执行res.redirect时传递标头