admin管理员组

文章数量:1334697

I have a cookie on my browser and I want to read it with react, I use it like that:

import Cookies from 'js-cookie';
console.log(Cookies.get('cookieName1'));

when I run it, I get undefined on the console, but, the cookieName1 have a value on my cookies.

How can I fix it ?

I have a cookie on my browser and I want to read it with react, I use it like that:

import Cookies from 'js-cookie';
console.log(Cookies.get('cookieName1'));

when I run it, I get undefined on the console, but, the cookieName1 have a value on my cookies.

How can I fix it ?

Share Improve this question edited Aug 13, 2019 at 14:57 ravibagul91 20.8k6 gold badges38 silver badges61 bronze badges asked Aug 13, 2019 at 14:10 Ichrak MansourIchrak Mansour 1,94212 gold badges37 silver badges64 bronze badges 13
  • 1 can your print just Cookies.get(); and show us what you see there...? – Arup Rakshit Commented Aug 13, 2019 at 14:14
  • 3 Are you sure the cookie is visible to JavaScript? A cookie set by a server can be marked as HttpOnly which means that it is not visible from JavaScript – NineBerry Commented Aug 13, 2019 at 14:14
  • Can you run console.log(document.cookie) and tell us what you get. – Mark Commented Aug 13, 2019 at 14:20
  • @ArupRakshit it return undefined – Ichrak Mansour Commented Aug 13, 2019 at 14:22
  • 3 @CodeLover Show us what you see there in developer tools. All the properties of the cookies – NineBerry Commented Aug 13, 2019 at 14:55
 |  Show 8 more ments

2 Answers 2

Reset to default 2

I have used js-cookies which works well.

import cookies from "js-cookies";

const secure = window.location.protocol === 'https'

to set value in cookie use below code

cookies.setItem("API_TOKEN", "hello", undefined, "/", undefined, secure)

to get value from cookie use below code

cookies.getItem("API_TOKEN")

to remove cookie use below code

cookies.removeItem('API_TOKEN')

if a cookie is marked as HttpOnly, it is not accessible on the client-side using JavaScript. The HttpOnly flag is a security feature for cookies that restricts them from being accessed by client-side scripts. This is done to mitigate the risk of cross-site scripting (XSS) attacks, where an attacker injects malicious scripts into a website, and those scripts attempt to steal sensitive information, such as cookies.

本文标签: javascriptHow to read cookies with reactStack Overflow