为什么没有在重定向上设置我的标头? [英] Why is my header not being set on redirect?

查看:72
本文介绍了为什么没有在重定向上设置我的标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一条express路线.我设置了headercookie,然后重定向.

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被设置并可用.我没有名为TESTheader.为什么没有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:

  1. 将其放在查询字符串中作为重定向URL的参数.当重定向的请求传入时,您的服务器将看到该查询字符串.
  2. 设置cookie.然后,当重定向请求进入时,服务器可以查看cookie.
  3. 在服务器端会话对象中设置数据,可在下一个请求时访问.然后,您的服务器可以在重定向请求进入时查看会话.
  1. 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.
  2. Set a cookie. Your server can then look at the cookie when the redirected request comes in.
  3. 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.

这篇关于为什么没有在重定向上设置我的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆