【问题标题】:How can i access the cookie sent as a response from express in react js?我如何访问在 react js 中作为 express 响应发送的 cookie?
【发布时间】:2020-08-10 04:32:24
【问题描述】:

我正在使用 mern stack 来制作应用程序。对于身份验证,我使用带有护照身份验证的 toke auth,出于安全原因,我在 cookie 中发送令牌。我有一个登录调用,它返回一个带有响应的 cookie。 sn-p 如下:

    res.cookie("cookie_token", token, { maxAge: 84600 });
    res.send({
        status: "success"
    });

我可以在邮递员甚至网络浏览器中看到 cookie(xhr 请求)。

我正在使用 axios 来调用 react js 中的登录 api。

 axios.get(myapiurl, {
        headers: {
          email: fields.email,
          password: fields.password,
          "access-control-allow-origin": "*"
        }
      })
        .then(res => {
            console.log(res);
        }).catch((err) => {
          console.log(err);
        });

虽然我找不到 sn-p 来访问 react js 中的 cookie。我该如何解析它?我看不到响应 axios 的 cookie 吗?我怎样才能访问它。

【问题讨论】:

    标签: reactjs express cookies


    【解决方案1】:

    请试试这个。来自 mdn 的片段。

    function getCookie(sKey) {
      if (!sKey) { return null; }
      return document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + sKey.replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1") || null;
    }
    
    export function getLoginInfo() {
      const cookieToken = getCookie('cookie_token')
       console.log(cookieToken)
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-23
      • 1970-01-01
      • 2016-06-22
      • 2014-08-24
      • 2020-08-14
      • 1970-01-01
      • 2017-03-21
      • 2019-03-10
      相关资源
      最近更新 更多