search

Home  >  Q&A  >  body text

Use Fetch API to pass cookies

<p>I'm trying to use the new Fetch API and I'm having trouble handling cookies. Specifically, after a successful login, there is a Cookie header in future requests, but Fetch seems to ignore this header and all requests I make using Fetch are unauthorized. </p> <p>Is this because Fetch is not ready yet, or does Fetch not support Cookies? </p> <p>I use Webpack to build my application. I'm also using Fetch in React Native and don't have the same problem. </p>
P粉066725148P粉066725148523 days ago633

reply all(2)I'll reply

  • P粉106711425

    P粉1067114252023-08-22 15:30:15

    In addition to @Khanetor's answer, for those who are dealing with cross-origin requests, you can use credentials: 'include'

    Example JSON fetch request:

    fetch(url, {
      method: 'GET',
      credentials: 'include'
    })
      .then((response) => response.json())
      .then((json) => {
        console.log('Gotcha');
      }).catch((err) => {
        console.log(err);
    });

    https://developer.mozilla.org/en-US/docs/Web/API/Request/credentials

    reply
    0
  • P粉818088880

    P粉8180888802023-08-22 15:21:43

    By default, Fetch does not use cookies. To enable cookies, do the following:

    fetch(url, {
      credentials: "same-origin"
    }).then(...).catch(...);
    

    reply
    0
  • Cancelreply