美文网首页
ajax、axios、fetch

ajax、axios、fetch

作者: janezhang | 来源:发表于2020-04-10 15:55 被阅读0次

fetch:

是一种HTTP数据请求的方式,是XMLHttpRequest的一种替代方案。fetch不是ajax的进一步封装,而是原生js。Fetch函数就是原生js,没有使用XMLHttpRequest对象。
具体fetch内容:
http://undefinedblog.com/window-fetch-is-not-as-good-as-you-imagined/?utm_source=caibaojian.com

缺点:
  • fetch只对网络请求报错,对400,500都当做成功的请求,需要封装去处理
  • fetch对请求回来的json格式是ReadableStream流的形式。
  • fetch默认不会带cookie,需要添加配置项fetch(url, {credentials: 'include'})
  • fetch不支持abort,不支持超时控制,使用setTimeout及Promise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了流量的浪费
  • fetch没有办法原生监测请求的进度,而XHR可以
  • 所有版本的 IE 均不支持原生 Fetch,fetch-ie8 会自动使用 XHR 做 polyfill。但在跨域时有个问题需要处理。IE8, 9 的 XHR 不支持 CORS 跨域,不支持传 Cookie!所以推荐使用 fetch-jsonp
fetch封装:
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',//为了在当前域名内自动发送 cookie , 必须提供这个选项
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "cors",//请求的模式
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        
        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else {   //ajax+promise
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}

axios:

具体点:中文:https://www.kancloud.cn/yunye/axios/234845
官方:http://www.axios-js.com/docs/

  1. 从 node.js 创建 http 请求
  2. 支持 Promise API
  3. 客户端支持防止CSRF(请求中携带cookie)
  4. 提供了一些并发请求的接口(重要,方便了很多的操作)
  5. 丰富的api, Interceptors, 并发:
1)各种ajax的api别名,
  • axios.request(config)

  • axios.get(url[, config])

  • axios.delete(url[, config])

  • axios.head(url[, config])

  • axios.post(url[, data[, config]])

  • axios.put(url[, data[, config]])

  • axios.patch(url[, data[, config]])

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

2)创建实例,还有一些实例方法

axios.create([config])

var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

实例方法:

  • axios#request(config)

  • axios#get(url[, config])

  • axios#delete(url[, config])

  • axios#head(url[, config])

  • axios#post(url[, data[, config]])

  • axios#put(url[, data[, config]])

  • axios#patch(url[, data[, config]])

3)处理并发请求的助手函数:

a. axios.all(iterable)
b. axios.spread(callback)

4)拦截器:
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

相关文章

  • 【vue学习】axios

    Ajax、fetch、axios的区别与优缺点 axios的github地址 原生ajax jqueryAjax ...

  • React中的“ajax”

    React没有ajax模块 集成其他的js库(如axios/fetch/jquery),发送ajax请求axios...

  • 2019-03-08

    ajax和axios、fetch的区别 xhr状态和事件触发

  • React第五天 (偷懒了一天)

    React与后台数据交互 axios: fetch: 传统 Ajax 已死,Fetch 永生:https://se...

  • vue学习4

    接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环...

  • Vue接口调用方式

    接口调用方式 原生ajax 基于jQuery的ajax fetch axios 异步 JavaScript的执行环...

  • 前端网络请求

    前端网络请求的方式主要有 Ajax ,jQuery封装的 Ajax,fetch,axios、request 等开源...

  • 5.axios

    axios是一种对ajax的封装,传统 ajax 指的是 XMLHttpRequest(XHR),fetch是一种...

  • Ajax, Axios, Fetch区别

    本文将会根据自己的理解,来阐述Ajax, Axios, Fetch他们之间的区别 1 、JQuery ajax A...

  • 08、axios

    axios是一种对ajax的封装,传统 ajax 指的是 XMLHttpRequest(XHR),fetch是一种...

网友评论

      本文标题:ajax、axios、fetch

      本文链接:https://www.haomeiwen.com/subject/vsecuhtx.html