【问题标题】:How to read the cookie on the client side (react) that was set via Passport on the Server side (node-express)?如何读取通过服务器端 (node-express) 上的 Passport 设置的客户端 (react) cookie?
【发布时间】:2020-11-26 21:10:33
【问题描述】:

如何在服务器端(node-express)读取通过 Passport 设置的客户端(react)cookie?

cookie设置正确,可以在服务器端进行序列化和反序列化,如下代码所示:

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

如何在客户端(React)读取这个 cookie?

我对 cookie 没有太多经验,但我见过以下解决方案:

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

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

//  more code....
}  


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....  

还有很多其他的......但看起来你必须知道username 或key 才能获得它的价值。由于 Passport.js 在 serializeUser 方法中创建了我的 cookie,我不知道 key 的值是什么。有谁知道键值是什么或如何读取护照创建的 cookie?

【问题讨论】:

  • 你在浏览器的开发工具中看到cookie了吗?

标签: node.js reactjs cookies authorization passport.js


【解决方案1】:

cookie 将是仅 HTTP 且在客户端不可读。但是,您可以轻松地做到这一点:

  • 创建服务器端 API 路由
  • 也许在 GET /api/user/current
  • 此端点执行上述 cookie 反序列化然后返回一个 JSON 对象

然后,客户端浏览器代码对上述端点执行 Ajax GET。

【讨论】:

  • 谢谢,我也考虑过!我没有太多使用 cookie 的经验,但不是 cookie 的主要用例之一,我可以在客户端解码 cookie,这样我就不必向服务器发出获取请求授权?如果我必须向服务器发出 fetch 请求,那么一开始就没有 cookie,我是对的还是我对 cookie 的目的感到困惑?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 2020-04-18
  • 2019-11-26
  • 2018-07-24
  • 1970-01-01
  • 2017-10-18
相关资源
最近更新 更多