How can I set a cookie in react?

后端 未结 7 2245
忘了有多久
忘了有多久 2020-11-30 20:09

Orginally, I use the following ajax to set cookie.

function setCookieAjax(){
  $.ajax({
    url: `${Web_Servlet}/setCookie`,
    contentType: \'application/         


        
7条回答
  •  青春惊慌失措
    2020-11-30 20:45

    By default, when you fetch your URL, React native sets the cookie.

    To see cookies and make sure that you can use the https://www.npmjs.com/package/react-native-cookie package. I used to be very satisfied with it.

    Of course, Fetch does this when it does

    credentials: "include",// or "some-origin"
    

    Well, but how to use it

    --- after installation this package ----

    to get cookies:

    import Cookie from 'react-native-cookie';
    
    Cookie.get('url').then((cookie) => {
       console.log(cookie);
    });
    

    to set cookies:

    Cookie.set('url', 'name of cookies', 'value  of cookies');
    

    only this

    But if you want a few, you can do it

    1- as nested:

    Cookie.set('url', 'name of cookies 1', 'value  of cookies 1')
            .then(() => {
                Cookie.set('url', 'name of cookies 2', 'value  of cookies 2')
                .then(() => {
                    ...
                })
            })
    

    2- as back together

    Cookie.set('url', 'name of cookies 1', 'value  of cookies 1');
    Cookie.set('url', 'name of cookies 2', 'value  of cookies 2');
    Cookie.set('url', 'name of cookies 3', 'value  of cookies 3');
    ....
    

    Now, if you want to make sure the cookies are set up, you can get it again to make sure.

    Cookie.get('url').then((cookie) => {
      console.log(cookie);
    });
    

提交回复
热议问题