通过React获取Cookie

时间:2018-06-29 21:21:20

标签: reactjs session cookies express-session react-cookie

我需要知道我的用户是否已连接。为此,我想读取在服务器端通过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 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;用户名= Ugo; SL_G_WPT_TO = fr; SL_GWPT_Show_Hide_tmp =未定义; SL_wptGlobTipTmp =未定义

感谢您的帮助!

6 个答案:

答案 0 :(得分:18)

您可以使用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....
}  

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

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

答案 1 :(得分:4)

我建议使用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://www.npmjs.com/package/universal-cookie

答案 2 :(得分:4)

不需要第三方 npm 包。您可以使用纯 JS 来提取 cookie。这是一个自定义函数:

function getCookie(key) {
  var b = document.cookie.match("(^|;)\\s*" + key + "\\s*=\\s*([^;]+)");
  return b ? b.pop() : "";
}

答案 3 :(得分:0)

如果您只想通过键获取cookie值,我建议您使用无任何依赖的纯JavaScript。

在此示例中,它在Regex的帮助下通过键“用户名”获取cookie值。

let cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");

https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Example_2_Get_a_sample_cookie_named_test2

答案 4 :(得分:0)

您也可以使用以下方法,无需任何 3rd 方软件包,如 developer.mozilla.org 中所述:

document.cookie
  .split('; ')
  .find(row => row.startsWith('YOUR-COOKIE='))
  .split('=')[1];

答案 5 :(得分:0)

我希望这个功能可以帮助:

function getCookie(name) {
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i].trim();
      if (cookie.substring(0, name.length + 1) === (name + '=')) {
        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
        break;
      }
    }
  }
  return cookieValue;
}