How to read the cookie on the client side (react) that was set via Passport on the Server side (node-express)?

吃可爱长大的小学妹 提交于 2020-08-26 13:32:21

问题


How to read the cookie on the client side (react) that was set via Passport on the Server side (node-express)?

The cookie is setup correctly and can be serialized and deserialized on the server side as shown in the below code:

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

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

How can I read this cookie on the client side (React)?

I don't have much experience with cookies, but I've seen the below solutions:

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

And many others... but it seems like to read the cookie you have to know the username or key to get the value of it. Since Passport.js created my cookie in the serializeUser method, I don't know what the key value is. Does anyone know what the key value is or how to read a cookie created by passport?


回答1:


The cookie will be HTTP Only and not readable on the client side. However, you can easily do this:

  • Create a server side API route
  • Perhaps at GET /api/user/current
  • This endpoint does the above cookie deserialization then returns a JSON object

The client side browser code then just does an Ajax GET to the above endpoint.



来源:https://stackoverflow.com/questions/63286397/how-to-read-the-cookie-on-the-client-side-react-that-was-set-via-passport-on-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!