ajaxSetup() equivalent for Fetch API

939 views Asked by At

I'm using the Fetch API for the first time. Does it have something akin to jQuery's ajaxSetup() method, in order to set authorization headers for future requests? I can't find any evidence that it does.

1

There are 1 answers

0
Jai Sandhu On BEST ANSWER

You can create authorisation headers using Request, saving to a variable allows it to be reusable. Note that according to the jQuery docs, setting default values using jQuery.ajaxSetup() is not recommended

let href = '/linkToPage';
let request = new Request(href, {
   method: 'GET',
   mode: 'same-origin',
   redirect: 'follow',
   headers: new Headers({
      'Content-Type': 'text/plain',
      'X-Requested-With': 'XMLHttpRequest'
   })
});

Then use the fetch request as usual

fetch(request).then((response) => {
   if(response.ok) {
      return response.text();
   }
   throw new Error('Network response was not ok.');
}).then((text) => {
   if(text.trim() != ''){
      console.log(text);
   }
}).catch((error) => {
   console.log(error);
});