我需要知道我的用户是否已连接。为此,我想读取我在服务器端使用express-session设置的cookie:
app.use(session({
secret: 'crypted key',
resave: false,
saveUninitialized: true,
cookie: { secure: false } // Put true if https
}))
app.post('/connect_user', (req, res) => {
req.session.cookie.username = req.body.username
findUserData('username', req.body.username, req, (userData) => {
req.session.cookie.id = userData.id
req.session.cookie.username = userData.username
res.redirect('/profil')
})
})
我尝试使用react-cookie
,但即使我复制粘贴了npm react-cookie
文档的示例,它也无法工作:
import React from 'react';
import Landing from './Landing';
import Home from './Home';
import Profil from './Profil';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { instanceOf } from 'prop-types';
import { Cookies } from 'react-cookie';
class App extends React.Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
username: cookies.get('username')
};
}
render() {
console.log(this.state.name)
let homePage = (!this.state.username) ? <Landing/> : <Home/>
return (
<Router>
<div>
<Route exact path='/' component={homePage}></Route>
<Route path='/profil' component={Profil}></Route>
</div>
</Router>
)
}
}
export default App;
这很奇怪,因为document.cookie
呈现了正确的结果,但我不知道如何处理它:
PHPSESSID=0nv9ic8h7pv2b63lu4v7eg3mop; user_id=21; username=Ugo; SL_G_WPT_TO=fr; SL_GWPT_Show_Hide_tmp=undefined; SL_wptGlobTipTmp=undefined
发布于 2018-06-30 12:38:24
您可以使用js-cookie
包,也可以使用npm install js-cookie --save
命令进行安装。
import React from 'react';
import Cookies from 'js-cookie';
class App extends React.Component {
this.state = {
username: Cookies.get('username')
}
// more code....
}
发布于 2019-09-07 02:46:21
如果您想要的只是通过键获取cookie值,我建议使用没有任何依赖项的纯javascript。
在本例中,它在Regex的帮助下通过键"username“获取cookie值。
let cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");
https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Example
发布于 2018-06-30 07:02:06
我推荐使用universal-cookie
,因为它更容易使用。请注意,cookies与React无关。它们存储在浏览器上,您可以使用浏览器的默认API来获取cookie。
下面是一个如何使用universal-cookies
的示例
import React from 'react';
// other imports...
import Cookies from 'universal-cookie';
const cookies = new Cookies();
class App extends React.Component {
this.state = {
username: cookies.get('username')
}
// more code....
https://stackoverflow.com/questions/51109559
复制相似问题