比较fetch和Axios

7次阅读

共计 1857 个字符,预计需要花费 5 分钟才能阅读完成。

基本语法

axios()

Axios 将带有自定义头部的 POST 请求发送到某个 URL。Axios 自动将数据转换为 JSON

// 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() 时,你必须手动完成。对比下:

// 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()做不到的事情。

HTTP 拦截器

在 Axios 中声明请求拦截器:

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.all()方法。只需将一个请求数组传递给这个方法,然后使用 axios.spread()将响应数组的属性分配给多个变量:

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');
}));

正文完
 0