Ajax、fetch和axios的区别

Ajax

传统 Ajax 指的是 XMLHttpRequest(XHR), 最早出现的发送后端请求技术,隶属于原始js中,核心使用XMLHttpRequest对象,多个请求之间如果有先后关系的话,就会出现回调地狱。

ajax封装:

//对原生Ajax方法进行封装
function ajax2(opt){
		opt = opt || {};
		opt.method = opt.method.toUpperCase() || 'POST';
		opt.url = opt.url || '';//请求地址 
		opt.async = opt.async || true;//是否异步请求
		opt.data = opt.data || null;//传输数据 
		opt.success = opt.success || function () {};//服务器响应成功进行相应的处理
		var xmlHttp = null;
		if (XMLHttpRequest) {
			xmlHttp = new XMLHttpRequest();//服务器请求对象
		}
		else {
			xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');//兼容微软请求对象
		}
		var params = [];
		for (var key in opt.data){
			params.push(key + '=' + opt.data[key]);
		}
		var postData = params.join('&');
		if (opt.method.toUpperCase() === 'POST') {//请求方法为POST,则执行如下操作
			xmlHttp.open(opt.method, opt.url, opt.async);
			xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
			xmlHttp.send(postData);
		}
		else if (opt.method.toUpperCase() === 'GET') {//请求方法为GET,则执行如下操作
			xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
			xmlHttp.send(null);
		}
		xmlHttp.onreadystatechange = function () {
			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {//响应是否成功
				var data = JSON.parse(xmlHttp.responseText);
				opt.success(data);
			}
		};
	}

JQuery ajax

是对原生XHR的封装,除此以外还增添了对JSONP的支持。

fetch

fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。

注意fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象

fetch是一个低层次的API,你可以把它考虑成原生的XHR,所以使用起来并不是那么舒服,需要进行封装。
例如:

  • fetch只对网络请求报错,对400500都当做成功的请求,服务器返回 400500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject。
  • fetch默认不会带cookie,需要添加配置项: fetch(url, {credentials: 'include'})
  • fetch不支持abort,不支持超时控制,使用setTimeoutPromise.reject的实现的超时控制并不能阻止请求过程继续在后台运行,造成了流量的浪费
  • fetch没有办法原生监测请求的进度,而XHR可以

文档:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

  • 从浏览器中创建 XMLHttpRequest
  • 支持 Promise API
  • 客户端支持防止CSRF
  • 提供了一些并发请求的接口(重要,方便了很多的操作)
  • 从 node.js 创建 http 请求
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据

axios使用:

//全局的 axios 默认值
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//拦截器
//在请求或响应被 then 或 catch 处理前拦截它们。
// 添加请求拦截器
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);
  });
 
//执行 GET 请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
//执行POST请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
//执行多个并发请求
function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // 两个请求现在都执行完成
  }));

中文文档:https://www.kancloud.cn/yunye/axios/234845

发布了34 篇原创文章 · 获赞 2 · 访问量 1655

猜你喜欢

转载自blog.csdn.net/liu_xiaoru/article/details/100751572