【问题标题】:Get cookie with react通过反应获取 cookie
【发布时间】:2018-12-09 02:39:19
【问题描述】:

我需要知道我的用户是否已连接。为此,我想使用 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      如果您只想通过键获取 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

      【讨论】:

        【解决方案3】:

        我建议使用universal-cookie,因为它更易于使用。请注意,cookie 与 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://www.npmjs.com/package/universal-cookie

        【讨论】:

        • 为什么人们一直添加这个??? class App extends React.Component {这在实际代码中不存在
        • @uberrebu 你不需要this.state = {。那只是如何使用 Cookies. Instead of this.state, you can do: const myCookieData = cookies.get('username')`的一个例子`
        【解决方案4】:

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

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

        【讨论】:

          【解决方案5】:

          您也可以使用下面的方法,而无需developer.mozilla.org 中记录的任何 3rd 方包:

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

          【讨论】:

            【解决方案6】:

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

            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;
            }
            

            【讨论】:

              【解决方案7】:
              cookie = key=>((new RegExp((key || '=')+'=(.*?); ','gm')).exec(document.cookie+'; ') ||['',null])[1]
              console.log(cookie('test'))
              

              【讨论】:

              • 在 Stack Overflow 上,如何 很重要,但网站质量水平的很大一部分来自人们不遗余力地解释 为什么。虽然仅代码的答案可以让提出问题的人克服他们可能面临的任何障碍,但从长远来看,这对他们或未来的访问者没有多大好处。见Is there any benefit in code-only answers?
              • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
              猜你喜欢
              • 2019-12-20
              • 1970-01-01
              • 2012-04-27
              • 2012-11-07
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2015-05-20
              • 1970-01-01
              相关资源
              最近更新 更多