axios
- 从 node.js 创建 http 请求。
- 支持 Promise API。
- 提供了一些并发请求的接口(重要,方便了很多的操作)。
- 在浏览器中创建 XMLHttpRequests。
- 在 node.js 则创建 http 请求。(自动性强)
- 支持 Promise API。
- 支持拦截请求和响应。
- 转换请求和响应数据。
- 取消请求。
- 自动转换 JSON 数据。
- 客户端支持防止CSRF。
- 客户端支持防御 XSRF
// 超时取消请求
axios.defaults.timeout = 10000;
axios.defaults.maxContentLength = Infinity;
// 设置 Content-Type
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
fetch用法:
try {
  let response = await fetch(url);
  let data = response.json();
  console.log(data);
} catch(e) {
  console.log("Oops, error", e);
}
优缺点:
- fetch号称是ajax的替代品,它的API是基于Promise设计的,旧版本的浏览器不支持Promise,需要使用polyfill es6-promise
- 符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
- 更加底层,提供的API丰富(request, response)
- 脱离了XHR,是ES规范里新的实现方式
- fetchtch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
- fetch默认不会带cookie,需要添加配置项
- post请求body内容不会自动做序列化,需要手动封装序列化
- fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了量的浪费
- fetch没有办法原生监测请求的进度,而XHR可以。
- 原生的fetch API没有提供timeout的处理,但是工程中是需要timeout机制的,比如:一个接口响应时间超过6秒就抛出提示信息,如何完成这个场景?
function serialize(o = {}) {
    let result = ''
    Object.keys(o).forEach(key => {
      let val = o[key]
      val = typeof o[key] == 'object' ? JSON.stringify(val) : val
      result += `&${key}=${val}`
    })
    return result.slice(1)
  }
fetch(url, {
  credentials: 'include',
  method: 'POST',
  headers: Object.assign({
    'Content-Type': 'application/x-www-form-urlencoded'
  }, headers),
  body: this.serialize(data)
})
.then(res => {
    let status = res.status
    if (status && status >= 200 && status < 400) {
        return res;
    } else {
        let error = new Error(res.statusText);
        error.response = res;
        error.statusCode = res.status;
        throw error;
    }
})
.then(res => res.json())
.catch(e => {
    return e
})
嗯 fetch就是有这么多缺点,但是调用方便呀,不依赖第三方呀 做个小demo啥的,信手拈来不香吗!