通过React获取Cookie [英] Get cookie with react

查看:188
本文介绍了通过React获取Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道我的用户是否已连接.为此,我想读取在服务器端通过express-session设置的cookie:

I need to know if my user is connected or not. For that I want to read the cookies that I set in the server side with express-session :

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 doc:

I tried to use react-cookie but it doesn't work however I copy/paste the npm react-cookie doc :

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

It's weird because document.cookie renders the correct result, but I don't know how handle it: PHPSESSID=0nv9ic8h7pv2b63lu4v7eg3mop; user_id=21; username=Ugo; SL_G_WPT_TO=fr; SL_GWPT_Show_Hide_tmp=undefined; SL_wptGlobTipTmp=undefined

推荐答案

您可以使用js-cookie软件包,也可以使用npm install js-cookie --save命令进行安装.

You can use js-cookie package and can install it using npm install js-cookie --save command.

import React from 'react';
import Cookies from 'js-cookie';

class App extends React.Component {
     this.state = {
        username: Cookies.get('username')
     }

//  more code....
}  

文档: https://github.com/js-cookie/js-cookie

NPM: https://www.npmjs.com/package/js-cookie

这篇关于通过React获取Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆