比較fetch()和Axios

基本語法

axios()

Axios將帶有自定義頭部的POST 請求發送到某個URL。Axios自動將數據轉換爲JSONios

// axios

const options = {
  url: 'http://localhost/test.htm',
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  data: {
    a: 10,
    b: 20
  }
};

axios(options)
  .then(response => {
    console.log(response.status);
  });

fetch()

// fetch()

const url = 'http://localhost/test.htm';
const options = {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json;charset=UTF-8'
  },
  body: JSON.stringify({
    a: 10,
    b: 20
  })
};

fetch(url, options)
  .then(response => {
    console.log(response.status);
  });

對二者總結

  • 發送數據時,fetch()使用body屬性,而Axios使用data屬性
  • fetch()中的數據是字符串化的,JSON.stringify()
  • URL做爲參數傳遞給fetch()。可是在Axios中,URL是在options對象中設置的

JSON 數據自動轉換

Axios在發送請求時自動 stringify 數據(儘管你能夠覆蓋默認行爲並定義不一樣的轉換機制)。可是,在使用 fetch()時,你必須手動完成。對比下:git

// axios
axios.get('https://api.github.com/orgs/axios')
  .then(response => {
    console.log(response.data);
  }, error => {
    console.log(error);
  });

// fetch()
fetch('https://api.github.com/orgs/axios')
  .then(response => response.json())    // one extra step
  .then(data => {
    console.log(data) 
  })
  .catch(error => console.error(error));

自動轉換數據是一個很好的特性,但仍是那句話,它不是fetch()作不到的事情。github

HTTP 攔截器

在Axios中聲明請求攔截器:json

axios.interceptors.request.use(config => {
  // log a message before any HTTP request is sent
  console.log('Request was sent');

  return config;
});

// sent a GET request
axios.get('https://api.github.com/users/sideshowbarker')
  .then(response => {
    console.log(response.data);
  });

在這段代碼中, axios.interceptors.request.use()方法用於定義在發送HTTP請求以前要運行的代碼。axios

併發請求

要同時發出多個請求,Axios提供了 axios.all()方法。只需將一個請求數組傳遞給這個方法,而後使用axios.spread()將響應數組的屬性分配給多個變量:api

axios.all([
  axios.get('https://api.github.com/users/iliakan'), 
  axios.get('https://api.github.com/users/taylorotwell')
])
.then(axios.spread((obj1, obj2) => {
  // Both requests are now complete
  console.log(obj1.data.login + ' has ' + obj1.data.public_repos + ' public repos on GitHub');
  console.log(obj2.data.login + ' has ' + obj2.data.public_repos + ' public repos on GitHub');
}));
相關文章
相關標籤/搜索