为什么没有在重定向上设置我的标头?
我有一条express
路线.我设置了header
和cookie
,然后重定向.
I have an express
route. I set a header
and a cookie
and then I redirect.
router.get("/callback", async (req, res) => {
res.cookie("token", token, {
maxAge: COOKIE_EXPIRATION_MILLISECONDS
});
res.header("TEST", "HEADER");
res.redirect("/test");
});
当我按下/test
时,token
被设置并可用.我没有名为TEST
的header
.为什么没有header
?如何通过redirect
传递header
?
When I hit /test
, token
is set and available. I do not have a header
named TEST
. Why do I not have the header
? How do I pass the header
through the redirect
?
您的标头可能会与响应一起发送,但是当浏览器实际遵循重定向然后请求新URL时,您不会看到该标头.浏览器不这样做.请记住,当您执行res.redirect()
时,它将发送带有302状态和位置标头的响应.浏览器将看到302,并读取位置标头,然后向服务器发出新的浏览器请求以获取重定向的位置.先前响应的标头不会添加到对重定向位置的新请求中.
Your header is likely being sent with the response, but you won't see that header when the browser actually follows the redirect and then requests the new URL. Browsers don't do that. Remember, when you do res.redirect()
, it sends a response with a 302 status and a location header. The browser sees that 302 and reads the location header and then makes a new browser request to your server for the redirected location. Headers from the previous response are NOT added to the new request for the redirected location.
通常将这样的数据传递给重定向的请求的方法是:
The usual ways to pass data like this to a redirected requests are:
- 将其放在查询字符串中作为重定向URL的参数.当重定向的请求传入时,您的服务器将看到该查询字符串.
- 设置cookie.然后,当重定向请求进入时,服务器可以查看cookie.
- 在服务器端会话对象中设置数据,可在下一个请求时访问.然后,您的服务器可以在重定向请求进入时查看会话.
- Put it in the query string for the redirected URL as a parameter. Your server will then see that query string when the redirected requests comes in.
- Set a cookie. Your server can then look at the cookie when the redirected request comes in.
- Set data in a server-side session object that can be accessed on the next request. Your server can then look at the session when the redirected request comes in.
只有上面的第一个选项(查询参数)是完全安全的,因为如果同一用户发出其他请求,其他选项可能会混淆数据属于哪个请求.
Only the first option above (query parameter) is entirely safe because the others can get confused about which request the data belongs to if there are other requests coming in from that same user.