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
2 Answers
Reset to default 2I 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
版权声明:本文标题:javascript - How to read cookies with react? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742350872a2458463.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论