在模拟 Axios 的封装中,你可以考虑实现以下一些可配置的属性:
-
method
: 请求方法,如 GET、POST、PUT、DELETE 等。 -
url
: 请求的 URL。 -
headers
: 请求头,可以设置各种自定义的请求头字段。 -
data
: 请求体数据,可以是对象、字符串或 FormData 对象。 -
params
: 请求参数,可以作为 URL 的查询参数拼接在 URL 后面。 -
timeout
: 请求超时时间,可以设置一个毫秒数,超过该时间则视为请求超时。 -
withCredentials
: 是否允许发送跨域请求时携带凭证信息(如 Cookie)。 -
onUploadProgress
: 上传进度回调函数,用于监听上传进度。 -
onDownloadProgress
: 下载进度回调函数,用于监听下载进度。 -
transformRequest
: 请求数据的转换函数,用于修改请求数据的格式。 -
transformResponse
: 响应数据的转换函数,用于修改响应数据的格式。 -
validateStatus
: 响应状态码验证函数,用于自定义响应状态码的判断逻辑。 -
baseURL
: 基础 URL,可以设置一个统一的基础 URL,方便在请求中使用相对路径。
这些可配置的属性可以根据你的需求进行扩展和修改,以满足不同场景的请求需求。
const myAxios = (config) => {
return new Promise((resolve, reject) => {
//XHR 请求
//调用成功失败执行的函数
const xhr = new XMLHttpRequest();
//判断有没有参数,封装参数
if(config.params){
//自己写的方法
// config.url += '?'
// for(let key in config.params){
// config.url += key + '=' + config.params[key] + '&'
// }
// config.url = config.url.replace(/&$/, '')
// console.log(config.url);
//使用URLSearchParams转换,并携带到url上
const paramsObj = new URLSearchParams(config.params)
const queryString = paramsObj.toString()
config.url += `?${queryString}`
//http://hmajax.itheima.net/api/area?pname=%E8%BE%BD%E5%AE%81%E7%9C%81&cname=%E5%A4%A7%E8%BF%9E%E5%B8%82
console.log(config.url);
}
xhr.open(config.method || 'GET', config.url)
//设置超时时间
xhr.timeout = config.timeout || 0
//判断有没有请求头,封装请求头
//设置请求头要在open()之后,send()方法之前
if(config.headers){
for(let key in config.headers){
xhr.setRequestHeader(key, config.headers[key]);
}
}
xhr.onloadend = () => {
if(xhr.status >= 200 && xhr.status < 400){
resolve(JSON.parse(xhr.response) )
}else{
reject(new Error(xhr.response))
}
}
// 监听请求错误事件
xhr.onerror = function () {
reject(new Error('Network Error'));
};
// 监听请求超时事件
xhr.ontimeout = function () {
reject(new Error('Request Timeout'));
};
if(config.data){
//将对象转化为JOSN字符串的形式
xhr.send(JSON.stringify(config.data) || {});
}else{
xhr.send()
}
})
}
//get 获取省份数据
myAxios({
url: 'http://hmajax.itheima.net/api/province'
}).then(res =>{
console.log(res);
}).catch(error =>{
document.querySelector('body').innerHTML = error.message;
})
//get 获取地区列表
myAxios({
url:'http://hmajax.itheima.net/api/area',
method: 'GET',
params: {
pname: '辽宁省',
cname: '大连市'
}
}).then(res => {
console.log(res);
}).catch(error =>{
document.querySelector('body').innerHTML = error.message;
})
//post登录
myAxios({
url: 'http://hmajax.itheima.net/api/login',
method :'POST',
headers: {
'Content-Type': 'application/json'
},
data: {
username: '122322223',
password: '112323456'
}
}).then(res => {
console.log(res);
}).catch(error =>{
document.querySelector('body').innerHTML = error.message;
})