使用 Fetch API还是其它高级别的库比如axios


相对来说使用 类似axios的库,还有其它比如:JQuery的$.ajax(); Angular的 $http, superagent.

使用fetch当然可以做到任何你想要实现的功能,但是我们看看代码:

使用axios我们也就一行代码完成了调用:

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

如果不用http的toolkits那么我们需要写下面这么多的代码:

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});
      }
    });
  });
}
阅读量: 706
发布于:
修改于: