如何在React应用程序中访问浏览器Cookie [英] How to access a browser cookie in a react app
问题描述
这个问题有点流行,但是我没有那么幸运.我主要是一个后端人,所以我会随着学习而学习.
This question is a bit popular but Im not having such luck. Im mostly a backend person so Im learning as I go along.
我有一个名为 connect.sid
的cookie,其值为 12345
.我在chrome开发工具中看到了这一点.
I have a cookie named connect.sid
and value of 12345
. I see this in my chrome dev tools.
在我的React应用程序中,我控制台记录了 document.cookie
和 localStorage.getItem('connect.sid')
.我得到空值.如何获取 12345
的值?
In my react app I console logged document.cookie
and localStorage.getItem('connect.sid')
. Im getting null values. How to get the value of 12345
?
Passportjs ,使用passport-github2策略创建了该Cookie.我需要访问它,以便可以与我的API通讯.
Passportjs, using passport-github2 strategy, created this cookie. I need access to it so I could talk to my API.
谢谢
推荐答案
使用 react-cookie
可能是获取cookie值的最简单方法.您可以运行 npm install react-cookie
,即会安装v2.如果您只想在客户端上使用简单的API,我建议您使用v1.只需运行 npm install react-cookie@1.0.5
,从'react-cookie'中添加 import cookie到您的文件中,然后使用
cookie.load('connect.sid')
来获取Cookie值.您可以查看v1的自述文件.
Using react-cookie
may be the easiest way to get cookie value. You can run npm install react-cookie
, the v2 will be installed. If you only want to use a simple API only on the client, i will suggest to use v1. Just run npm install react-cookie@1.0.5
, add import cookie from 'react-cookie'
to you file and use cookie.load('connect.sid')
to get cookie value. You can check the README of v1 for detail.
如果仍然无法获取Cookie值,请确认:
If you still cannot get the cookie value, please confirm:
- 如果您希望在所有页面上都可以访问cookie,则将cookie设置为正确的路径,例如
/
. - 该cookie不是 httpOnly cookie ,HttpOnly无法通过JavaScript访问Cookie.
- the cookie is set to correct path like
/
, if you want your cookie to be accessible on all pages. - the cookie is not httpOnly cookie, HttpOnly cookies aren't accessible via JavaScript.
这篇关于如何在React应用程序中访问浏览器Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!