【问题标题】:Saving set-cookie value to browser cookies in React在 React 中将 set-cookie 值保存到浏览器 cookie
【发布时间】:2020-12-11 02:43:42
【问题描述】:

我从服务器获取了这个 cookie 值,我想把它保存到我的浏览器中。

Set-Cookie: succeeedd=noooo!; Path=/

我试过了

   const res = yield axios.post(`${config.authURL}/login`, data, {
      headers: {
        'Content-Type': 'application/json',
        Cookie: 'cookie1=value',
      },
    });

const res = yield axios.post(
  `${config.authURL}/login`,
  data,
  {
    headers: {
      'Content-Type': 'application/json',
    },
  },
  { withCredentials: true })

两者都没有将 cookie 保存到浏览器 cookie 中。如何将 Set-Cookie 值保存到浏览器,以便我可以使用它们进行身份验证?

【问题讨论】:

  • 检查this{ withCredentials: true } 应该在第三个参数中。不是第四个。
  • 有什么方法可以将它与 {headers: {}} 一起使用吗?

标签: reactjs cookies axios


【解决方案1】:

如下传递withCredentials: true

const res = yield axios.post(
  `${config.authURL}/login`,
  data,
  {
    headers: { 'Content-Type': 'application/json' },
    withCredentials: true
  }
);

对于更通用的配置,

// You can add it in a separate config file
const request = axios.create({ withCredentials: true });

// While making API call
request.post(`${config.authURL}/login`, data, { headers: {...} });

查看here了解更多详情。

【讨论】:

    【解决方案2】:

    安装universal-cookienpm

    import Cookies from 'universal-cookie';
    
    const cookies = new Cookies();
    
    axios.post(URL, data, {
        headers: {
          'Content-Type': 'application/json',
        },
        { withCredentials: true }
      })
      .then((res) => {
        let name = res.data.blobName;
        let value = res.data.blobValue;
        cookies.set(`${name}`, `${value}`);
      })
      .catch(function (error) {
        console.log(error);
      });
    
    
    
    

    【讨论】:

    • 但是,我怎样才能从服务器获取值并将其保存为 cookie?
    猜你喜欢
    • 2023-03-25
    • 2021-11-03
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多