How to access a browser cookie in a react app

后端 未结 4 709
你的背包
你的背包 2021-02-10 20:43

This question is a bit popular but Im not having such luck. Im mostly a backend person so Im learning as I go along.

I have a cookie named connect.sid and v

相关标签:
4条回答
  • 2021-02-10 21:27

    You can start by npm install react-cookiethen import { Cookies } from 'react-cookie' and finally cookies.get('connect.sid'):

    don't forget to wrap your root app inside CookiesProvider something like so :

      <CookiesProvider>
        <App />
      </CookiesProvider>
    

    You can find an example here

    0 讨论(0)
  • 2021-02-10 21:32

    I know that answer is not exactly what you want, but if you just want to authorize someone on the serverside i have an easy solution. Just add

    credentials: 'same-origin'

    to your AJAX request. If you have done that the cookie will get send with your connect.sid to the server and the server will handle the authentification for you.

    0 讨论(0)
  • 2021-02-10 21:36

    Full example using the react-cookie v2.

    You need to wrap your root component in and also the individual components where you want to access the cookies in withCookies(..). The cookies are then part of props.

    client.js:

    import {CookiesProvider} from "react-cookie";
    
    <CookiesProvider>
      <App />
    </CookiesProvider>
    

    App.js:

    import React from "react";
    import {withCookies} from 'react-cookie';
    
    class App extends React.Component {
      render() {
        const {cookies} = this.props;
        return <p>{cookies.get('mycookie')}</p>
      }
    }
    
    export default withCookies(App);
    
    0 讨论(0)
  • 2021-02-10 21:38

    Using react-cookie may be the easiest way to get cookie value. You can run npm install react-cookie, the v2 will be installed. If you only want to use a simple API only on the client, i will suggest to use v1. Just run npm install react-cookie@1.0.5, add import cookie from 'react-cookie' to you file and use cookie.load('connect.sid') to get cookie value. You can check the README of v1 for detail.

    If you still cannot get the cookie value, please confirm:

    1. the cookie is set to correct path like /, if you want your cookie to be accessible on all pages.
    2. the cookie is not httpOnly cookie, HttpOnly cookies aren't accessible via JavaScript.
    0 讨论(0)
提交回复
热议问题