简体   繁体   English

使用“react-cookie”时,Cookie 在浏览器中自行设置

[英]Cookie getting set on its own in browser when using 'react-cookie'

I am using a package known as 'react-cookie' for a project.我正在为一个项目使用称为“react-cookie”的 package。 It is working as expected and the cookie is being set as wanted.它按预期工作,并且正在根据需要设置 cookie。

Set cookie code (it gets set after user logs in)设置 cookie 代码(在用户登录后设置)

 setCookie('token', res.token, {path: '/'});

This code sets the cookie as wanted but whenever I go to user profile which has '/profile/info' route, an extra cookie of the same name gets set as undefined.此代码根据需要设置 cookie,但每当我将 go 设置为具有“/profile/info”路由的用户配置文件时,就会将一个额外的同名 cookie 设置为未定义。 My code does not have any setCookie function besides the one above.除了上述之外,我的代码没有任何 setCookie function 。 I cannot resolve why the extra cookie gets added when visiting the profile page.我无法解决为什么在访问个人资料页面时会添加额外的 cookie。 I don't think the dependency array of useEffect is causing any issue here.我不认为 useEffect 的依赖数组在这里引起任何问题。 Need a solution to prevent this.需要一个解决方案来防止这种情况。

Profile page code个人资料页面代码

const [cookies] = useCookies();
let token = cookies.token;

useEffect(() => {
    const getProfile = async () => {
      try {
        const response = await axios.get(`${url}api/profile/show`, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
         setInfo(response.data.userinfo);
      } catch (err) {
        console.log(err);
      }
    };
    getProfile();
  }, [token]);

Screenshot of the cookies cookies的截图

访问个人资料页面时,会自行添加第二个 cookie

You must get the value of token like this:您必须像这样获取令牌的值:

let token = cookies.get('token',  {path: '/'});

Your code is like to set the token again:您的代码就像再次设置token

let token = cookies.token; => setCookie('token', undefined, {path: 'currentPath'});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM