我需要知道我的用户是否连接。为此,我想阅读我在服务器端用 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