【问题标题】:Send cookie with get request使用 get 请求发送 cookie
【发布时间】:2020-01-24 04:16:20
【问题描述】:

我正在使用站点 https://a.com 进行身份验证。验证后,我访问http://b.com。当我从 b.com 向 a.com 发出 get 请求时,a.com 为我需要发送的会话设置了一个 cookie。

您能否告诉我,我如何获取 cookie 并将其与我的请求一起传递。

我尝试使用“withCredentials”发送请求:true, 还尝试将 axios-cookiejar-support 与 strong-cookie 一起使用。但是好像没用。

    .get(a.com/path-requiring-cookie, {
      withCredentials: true,
      headers: {
        'Content-Type': 'application/json',
        'access-control-allow-credentials': true,
      },
    })
    .then(res => {
      console.log(res.data);
    });```

This is the code that I have to send the request.

But this doesn't seem to send the cookie with the request.  Can someone please clarify.

【问题讨论】:

    标签: javascript cookies axios


    【解决方案1】:

    为什么不使用 javascript 函数来帮助使用基于它的名称获取 Cookie,如下所示

    function GetCookie(cName) {
      const name = `${cName}=`;
      const decodedCookie = decodeURIComponent(document.cookie);
      const ca = decodedCookie.split(';');
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') {
          c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
          return c.substring(name.length, c.length);
        }
      }
      return '';
    };
    
    console.log(GetCookie("SID"))

    【讨论】:

      【解决方案2】:

      看看this question

      您要解决的问题是从/向不同域读取/发送 cookie。

      如之前链接的问题中所述,一种解决方案是在 http://b.com 上设置一些标题

      Access-Control-Allow-Origin: http://b.com
      Access-Control-Allow-Credentials: true
      

      您在域为 http://b.com 的服务器上执行此操作

      类似的东西应该可以为您解决问题。

      【讨论】:

        猜你喜欢
        • 2015-12-07
        • 2016-01-25
        • 2014-12-18
        • 2016-07-07
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        • 2018-08-27
        • 1970-01-01
        相关资源
        最近更新 更多