【问题标题】:How do I create a cookie after a response from the server? react服务器响应后如何创建 cookie?反应
【发布时间】:2021-11-08 03:36:57
【问题描述】:

我有一个对服务器的授权请求:

axios
    .post(
      "http://localhost:5000/api/auth/sign-in",
      { ...values },
    )
    .then((res) => {
      const { token } = res.data;
     //there I need to save coookie with token that came from server
    })

授权成功后,服务器发送token,如何将token保存在带有httpOnly标志的cookie中?

【问题讨论】:

标签: reactjs


【解决方案1】:

您可以使用universal-cookie 包来执行此操作:https://www.npmjs.com/package/universal-cookie

import Cookies from 'universal-cookie';
 
const cookies = new Cookies();

...

.then((res) => {
  const { token } = res.data;
 cookies.set('token', token , { httpOnly: true, path: "/" });
})

【讨论】:

  • 由于某种原因cookie没有保存
  • 你怎么知道它没有保存?
  • 保存 cookie 时,我看到我已登录,但在 cookie 选项卡中看不到 cookie 已保存
  • 你知道为什么cookie不想保存吗?
  • 您可以添加path 以确保您应用中的所有页面都可以使用此cookie
猜你喜欢
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2014-02-11
  • 2021-04-06
  • 2021-11-29
  • 1970-01-01
相关资源
最近更新 更多