前言
说实话,从接触前端开始。接口请求直接用的就是JQuery的ajax,而我们如今的项目也直接用的是axios。至于底层一点的原理我们也不会刻意的去研究。最近正好有用node写一些小工具,需要自己封装AJAX,对这块做一下记录。
下面将介绍到:
- 分别封装node环境以及浏览器环境的AJAX
- 将callback模式转换为promise模式
node环境
// 引入node自带的http模块
const http = require('http')
// 将协议、主机名、端口等从uri中提出,这里我也用的是别人写好的,就不在这里展示了
const parseUrl = require('./parseUrl')
const ajax = async (param = {}, data = null) => {
const {method, url, userInfo } = param
const { protocol, hostname, path, port } = parseUrl(url)
// 配置请求头
let headers = {
"User-Info": userInfo,
"Content-Type": "application/json"
}
// 配置请求的参数
const requestOption = {
protocol,
host: hostname,
method,
path,
port,
headers
}
// 示例化promise类,请求成功则调用resolve,失败则调用reject
const promise = new Promise((resolve, reject) => {
const req = http.request(requestOption, result => {
//设置编码方式
result.setEncoding('utf8');
result.on('data', (chunk) => {
const r = JSON.parse(chunk)
if(r.code === 0) {
// 当请求成功,调用resolve,格式化并返回获取到的数据
resolve({
count: r.count || 0,
data: r.data
})
} else {
// 当请求失败则将请求到的错误返回
reject(r)
}
});
})
// 如果是post或put请求则将data写入
if (data) req.write(data);
req.end()
})
return promise
}
// 注意node环境的导出格式和浏览器环境的导出格式
module.exports = ajax
浏览器环境
// method: 'POST' 'PUT' 'GET' 'DELETE'
const ajax = function(method, url, data) {
return new Promise((resolve, reject) => {
// ActiveXObject 仅针对IE浏览器
const xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Mscrosoft.XMLHttp');
xhr.open(method, url, false);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
if (method === "POST" || method === "PUT") {
xhr.send(data) // data格式,username=admin&password=123456
} else {
xhr.send();
}
xhr.onreadystatechange = function(e) {
const status = e.currentTarget.status
if (e.currentTarget.readyState === 4 ) {
if (status === 200 || status === 204) {
resolve(xhr.responseText);
} else {
reject(new Error(xhr.responseText));
}
}
}
})
}
export default ajax
参考链接 http(node),XMLHttpRequest