NodeJS:header 使用 res.writeHead 的重定向缺少授权

NodeJS: header authorization missing from redirect using res.writeHead

我想将 HTTP 请求重定向到另一个 NodeJS 服务器。 我正在使用 res.writeHead 来重定向请求。

备选代码 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();

备选代码 2:

   let headers = Object.assign({},req.headers)
   headers['Location'] = ENV_CONFIG.ENV_US_URL + req.url
   res.writeHead( 307, {...headers} );
   res.end();

备选代码 3:

   let headers = Object.assign({},req.headers)
   res.writeHead( 307, {'Location': ENV_CONFIG.ENV_US_URL + req.url,...headers} );
   res.end();

三个备选方案提供相同的结果。 res headers 在发送到其他 NodeJS 服务器之前包含 authorization header。

当“新”请求到达另一个 NodeJS 服务器时,authorization header 丢失

请求 header DO 包含 authorization header.

为什么 authorization header 会落在那里?

顺便说一句。我试图在某些 custom header 中设置 authorization header 的值,它也丢失了。

Headers 像 auth headers 和其他自定义 headers 在您进行重定向时不会被浏览器保留。浏览器对您在重定向响应中指定的 location 形成新请求,并使用默认值 headers 构建该新请求,而不是使用重定向响应中的 headers。就好像用户在浏览器 URL 栏中输入了重定向的 URL 并且浏览器创建了一个新的默认请求到新的 URL.

您需要通过 URL 路径、查询参数或 cookie 将信息传递给重定向的请求。查询参数和 URL 路径将始终出现在重定向请求中,如果在重定向目标的域上设置了 cookie,则 cookie 将出现。

When the "new" request arrives to the other NodeJS server, the authorization header is missing

Headers 重定向浏览器时不会保留。浏览器创建一个新请求,默认为 headers 到重定向中指定的 location。您想要与新目标通信的任何信息都必须在重定向 URL(路径或查询参数)中或在目标域上设置的 cookie 中。