之前前端提到收集要求一般是指浏览器,但如今跟着 Node.js、小顺序的涌现,收集要求不再局限于浏览器。本文将带你相识差别要求的道理,以及如作甚项目挑选适宜的要求库。
1. 要求道理
1.1 浏览器
浏览器经由过程 XMLHttpRequest 对象完成 http 要求。
远古时代 ie6 是借助 ActiveXObject 对象完成 http 要求,如今已无人运用,不斟酌兼容。
W3C 规范新提出的 Fecth API,基于 Promise 完成,相对 XMLHttpRequest 对象挪用更轻易,但旧浏览器不支撑 Promise,须要对 Promise 举行 pollyfill。
- XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.send();
xhr.onreadystatechange = function() {
if(xhr.readyState === 4 && xhr.status === 200 ) {
let response = JSON.parse(xhr.responseText);
}
}
- Fetch
fetch(url)
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("error", e))
1.2 Node.js
Node.js 宣布于 2009 年,是一个基于 Chrome V8 引擎的 JavaScript 运转环境,Node.js 的顶层对象是 global,不存在 window 对象,不能经由过程 XMLHttpRequest 对象完成 http 要求。
Node.js 中经由过程引入 http/https/http2 模块完成 http 要求,下面为 http 模块完成的例子:
const http = require('http');
const server = http.createServer((req, res) => {
res.end('hello world');
});
server.on('clientError', (err, socket) => {
socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
server.listen(8000);
1.3 React Native
React Native 是 Facebook 2015 开源跨平台挪动运用开辟工具。
React Native 中已内置了 XMLHttpRequest API,同时供应了和 web 规范一致的Fetch API,所以大部份在 web 端能够运用的收集要求库在 React Native 中也能够运用。
1.4 Weex
Weex 是 阿里 2016 开源跨平台挪动运用开辟工具。
Weex 经由过程封装模块来挪用原生功用,供应了 stream 模块来完成收集要求。
1.5 小顺序
2017 年微信小顺序上线,随后各大平台都推出自身的小顺序。
小顺序由于要对 http 要求做参数校验、兼容各平台(iOS、Android)或版本题目,所以供应了一套属于自身的 API,不供应 window 对象。
下面为微信小顺序和支付宝小顺序的官网示例:
- 微信小顺序
wx.request({
url: 'test.php', // 仅为示例,并不是实在的接口地点
data: {
x: '',
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log(res.data)
}
})
- 支付宝小顺序
my.httpRequest({
url: 'http://httpbin.org/post',
method: 'POST',
data: {
from: '支付宝',
production: 'AlipayJSAPI',
},
dataType: 'json',
success: function(res) {
my.alert({content: 'success'});
},
fail: function(res) {
my.alert({content: 'fail'});
},
complete: function(res) {
my.hideLoading();
my.alert({content: 'complete'});
}
});
2. 要求库
从上文能够看出,平台间的要求体式格局存在种种差别,要求库就是为处理这类差别。下面为如今较火的要求库。
2.1 $.ajax(支撑浏览器)
$.ajax 为 jQuery 对 XMLHttpRequest 对象举行兼容封装。
须要补充的是 React Native 能够运用部份浏览器收集要求库,然则不能运用 jQuery,由于 jQuery 中还运用了许多浏览器中才有而 React Native 中没有的东西。
另外,如今运用框架的项目中我们一般采纳其他要求库,或许自身依据项目对 XMLHttpRequest 或 Fetch 举行封装,不会为了收集要求引入 jQuery。
2.2 Request(支撑 Node.js)
Request 是对 Node.js 的 http/https 模块封装的 http 库。
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
});
2.3 SuperAgent(支撑 Node.js)
SuperAgent 和 Request 相似,都是对 Node.js 的 http/https 模块封装的 http 库。
var request = require('superagent')
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.then(res => {
alert('yay got ' + JSON.stringify(res.body));
});
2.4 Axios(支撑 React Native,Node,浏览器)
Axios 是一个基于 promise 的 HTTP 要求库,能够用在浏览器和 Node.js 中。浏览器中运用 XMLHttpRequest,Node.js 中运用 http/https 模块。下面为要求示例:
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Vue 2.0 引荐运用 Axios 作为 Vue 的要求库。而且在 SSR 的时刻我们在服务端、客户端都须要要求,所以一般会挑选 Axios。
2.5 Fly.js(支撑 Node.js 、微信小顺序 、Weex 、React Native 、Quick App 和浏览器)
Fly.js 是一个基于 promise 的 HTTP 要求库,能够用在Node.js 、微信小顺序 、Weex 、React Native 、Quick App 和浏览器中,对上述平台都做了兼容。
fly.get('/user?id=133')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
除了 Fly.js,有些小顺序开辟框架自身供应收集要求库,对平台做了兼容,比方 Taro.request。
3. 总结
差别要求库之间的 API、运用都邑存在区分。项目开始时,依据须要兼容的平台挑选适宜的要求库,会大大削减今后代码重构的贫苦。
- 本文首发于民众号,更多内容迎接关注我的民众号: 阿夸座谈