1.代码
const request = ({ url = '', method = 'get', params = {}, data = {}, headers = {}, success, error }) => {
return new Promise((resolve, reject) => {
let xhr
if (window.XMLHttpRequest) xhr = new XMLHttpRequest()
else xhr = new ActiveXObject('MicroSoft.XMLHTTP')
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
let res = xhr.responseText;
success && success(JSON.parse(res))
resolve(JSON.parse(res))
} else {
error && error(xhr.status)
reject(xhr.status)
}
}
}
const setHeader = () => {
headers && Object.keys(headers).map(key => {
xhr.setRequestHeader(key, headers[key])
})
}
let reqUrl = url
if (Object.keys(params).length > 0) reqUrl += '?' + Object.keys(params).map(key => key + '=' + params[key]).join('&')
switch (method.toUpperCase()) {
case "GET":
case "DELETE":
case "OPTIONS":
case "HEAD":
case "TRACE":
case "CONNECT":
xhr.open(method, reqUrl);
setHeader()
xhr.send()
break
case "POST":
case "PUT":
xhr.open(method, reqUrl);
setHeader()
if (data instanceof FormData) {
xhr.send(data)
}
else if (Object.keys(data).length > 0) {
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(JSON.stringify(data))
}
else xhr.send()
break
}
})
}
2.使用
const BASE_URL = 'http://localhost:8080'
request({
url: BASE_URL + '/mes/list',
method: 'post',
headers:{
token:'token',
},
data: { a: 1, b: { c: 3 } },
}).then(res => {
console.log(res, 'post promise用法 res');
}).catch(errCode => {
console.log(errCode, 'post promise用法 errCode')
})
request({
url: BASE_URL + '/mes/list',
method: 'get',
params: { a: 1, b: 2 },
}).then(res => {
console.log(res, 'get promise用法 res');
}).catch(errCode => {
console.log(errCode, 'get promise用法 errCode')
})
request({
url: BASE_URL + '/mes/list',
method: 'get',
params: { a: 1, b: 2 },
success: (res) => {
console.log(res, 'get请求 回调用法 成功res')
},
error: (errCode) => {
console.log(errCode, 'get请求 回调用法 失败errCode')
}
})
request({
url: BASE_URL + '/mes/list',
method: 'post',
data: { a: 1, b: 2 },
success: (res) => {
console.log(res, 'post请求 回调用法 成功res')
},
error: (errCode) => {
console.log(errCode, 'post请求 回调用法 失败errCode')
}
})