简体   繁体   中英

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

I am using a package known as 'react-cookie' for a project. It is working as expected and the cookie is being set as wanted.

Set cookie code (it gets set after user logs in)

 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. My code does not have any setCookie function besides the one above. I cannot resolve why the extra cookie gets added when visiting the profile page. I don't think the dependency array of useEffect is causing any issue here. 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

访问个人资料页面时,会自行添加第二个 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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