fetch vs axios

2020-05-27  本文已影响0人  liuniansilence

axios

// 超时取消请求
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);
}

优缺点:

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啥的,信手拈来不香吗!

上一篇 下一篇

猜你喜欢

热点阅读