比较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');
}));
相关文章
相关标签/搜索