Repozytorium Web Developera

fetch vs axios

tldr; fetch można powiedzieć, że jest "niskopoziomowym" odpowiednikiem axios. Ponadto fetch domyślnie nie wspiera zabezpieczeń przed atakami XSRF.

Polecany artykuł.

All of the http toolkits I mentioned above (seriously, each and every one of them) treat a response with error status from the server (i.e. status 404, 500, etc.) as an error. However, fetch (similarly to XMLHttpRequest) rejects the promise only in case of network error (i.e. address could not be resolved, server is unreachable or CORS not permitted).

function addUser(details) {
  return axios.post('https://api.example.com/user', details);
}
vs

function addUser(details) {
  return fetch('https://api.example.com/user', {
    mode: 'cors',
    method: 'POST',
    credentials: 'include',
    body: JSON.stringify(details),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN')
    }
  }).then(response => {
    return response.json().then(data => {
      if (response.ok) {
        return data;
      } else {
        return Promise.reject({status: response.status, data});
      }
    });
  });
}