Reputation: 87
I want to redirect an HTTP request to another NodeJS server.
I am using the res.writeHead
in order to redirect the request.
Code alternative 1:
let headers = Object.assign({},req.headers)
await Object.entries(headers).forEach(async ([header,value]) => {
await res.setHeader(header,value)
})
await res.setHeader('Location',ENV_CONFIG.ENV_US_URL + req.url)
res.writeHead( 307 );
res.end();
code alternative 2:
let headers = Object.assign({},req.headers)
headers['Location'] = ENV_CONFIG.ENV_US_URL + req.url
res.writeHead( 307, {...headers} );
res.end();
code alternative 3:
let headers = Object.assign({},req.headers)
res.writeHead( 307, {'Location': ENV_CONFIG.ENV_US_URL + req.url,...headers} );
res.end();
The three alternatives deliver the same results.
The res
headers
do include the authorization
header before it sent to the other NodeJS server.
When the "new" request arrives to the other NodeJS server, the authorization
header is missing
The request header DO contain the authorization
header.
why would the authorization
header fall there?
BTW. I tried to set the value of the authorization
header
in some custom header, it went missing as well.
Upvotes: 1
Views: 1153
Reputation: 707148
Headers like auth headers and other custom headers are NOT preserved by the browser when you do a redirect. The browser forms a new request to the location
you specified in the redirect response and builds that new request with default headers, not with the headers from your redirect response. It is as if the user typed the redirected URL into the browser URL bar and the browser created a new, default request to that new URL.
You will need to pass information to the redirected request either via the URL path, via query parameters or via a cookie. Query parameters and the URL path will always be present on the redirected request and cookies will be present if the cookie is set on the domain of the redirected target.
When the "new" request arrives to the other NodeJS server, the authorization header is missing
Headers are not preserved when redirecting the browser. The browser creates a new request with default headers to the location
specified in the redirect. Any information you want to communicate to the new target must be either in the redirect URL (path or query parameters) or in a cookie that is set on the target domain.
Upvotes: 2