XHR 配置化请求库 基于 axios ⏲ 🚀
# npm
npm install axhr axios --save
# yarn
yarn add axhr axios
export interface XhrOptions {
url: string;
type?: string;
baseUrl?: string;
data?: Record<string, any>;
config?: XhrConfig;
headers?: Record<string, any>;
success?: (data: any, response: any) => any;
error?: (error: any) => any;
cancel?: (error: any) => any;
cancelMsg?: string;
before?: () => void;
end?: (result: any) => void;
}
export interface XhrProps {
request: (options?: XhrOptions) => Promise<any>;
baseUrl?: string;
defaultConfig?: ((options: XhrOptions) => any) | Partial<XhrConfig>;
baseData?: Record<string, any>;
getUrl?: (options: XhrOptions) => { baseUrl: string; url: string };
before?: (options: XhrOptions) => void;
success?: (options: XhrOptions, response: any) => any;
error?: (error: any, isCancel?: boolean) => any;
cancelXhr?: (msg: string, urls?: string[]) => any;
cancelMsg?: string;
end?: (result: any, isError?: boolean) => void;
}
xhr.request({
url: '/add',
type: 'GET',
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
baseUrl: 'https://some-domain.com/api/',
data: {},
config: {
...others
},
cancelMsg: '',
success: (res, response) => {},
error: res => {},
cancel: err => {},
});
- url:
url [required]
请求接口服务地址 - type:
type [required]
请求方式, 默认GET
- header:
header
自定义请求头, 默认'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
- baseUrl:
baseURL
基础地址, 除非url
是绝对地址,否则会加在url
前面 - data:
data
请求体参数,会根据配置自动转params
或data
- success: 请求成功响应, 使用
xhr.success
拦截需要返回true
- error: 请求失败响应 或
xhr.success
拦截返回false
- cancel: 取消请求响应
- cancelMsg: 取消请求提示信息
- config: 请求配置项,详情见https://github.com/axios/axios#request-config
- isCancelToken:
false
, 默认当前请求不参与取消请求; 也可以设置true
,独立token - noRepeat:
false
, 默认不判断重复请求,cancelToken
必须是true
将会取消还未响应结束的上一个重复请求
- isCancelToken:
搭配一些全局定义方法进行全局配置,对所有请求管用
全局默认配置, 将会合并进
config
xhr.defaultConfig = {
timeout: 10000,
withCredentials: true // cookie
};
// or
xhr.defaultConfig = () => {
return {
timeout: 10000,
withCredentials: true // cookie
}
}
全局基础参数, 将会合并进
config.data
xhr.baseData = {
t: Date.now() // IE catch
};
全局定义
baseUrl
优先级低于xhr.getUrl
全局动态设置获取
url
,baseUrl
const apiBaseUrl = '/oapi';
xhr.getUrl = option => {
if (option.baseUrl) {
return {
baseUrl: option.baseUrl,
url: option.url
};
}
return {
baseUrl: apiBaseUrl,
url: option.url
};
};
当请求成功时实现动态拦截配置, 也可以在这块做一些接口数据返回初步逻辑拦截
xhr.success = (res, resp) => {
let isSuccess = true;
if (typeof res === 'string') {
res = JSON.parse(res);
}
if (typeof res !== 'object') {
// console.error(apiUrl + ': response data should be JSON');
isSuccess = false;
}
switch (res.code + '') {
case '200':
isSuccess = true;
break;
default:
// console.error(res.message || 'unknown error');
isSuccess = false;
}
return isSuccess;
}
当请求失败时实现动态拦截配置,
xhr.error = (err, [isCancel]) => {}
手动调用取消请求,并传递取消信息
可以指定urls取消;不传urls则取消所有请求
xhr.cancelXhr(message, urls?: []);
请求前执行
xhr.before = () => {}
请求后执行
xhr.end = (res) => {}
简单示例
import xhr from 'axhr';
import {message} from 'antd';
import auth from './auth';
let apiUrl = '';
const apiBaseUrl = '/';
xhr.getUrl = option => {
if (option.baseUrl) {
apiUrl = option.baseUrl + option.url;
return {
baseUrl: option.baseUrl,
url: option.url
};
}
apiUrl = apiBaseUrl + option.url;
return {
baseUrl: apiBaseUrl,
url: option.url
};
};
xhr.baseData = {
t: Date.now()
};
xhr.defaultConfig = {
timeout: 10000,
withCredentials: true
};
xhr.success = (res, response) => {
let isSuccess = true;
if (typeof res !== 'object') {
message.error(apiUrl + ': response data should be JSON');
isSuccess = false;
}
switch (res.code + '') {
case '000000':
isSuccess = true;
break;
case '100006':
auth.toOutLogin();
isSuccess = false;
break;
case '100013':
auth.toOutLogin();
isSuccess = false;
break;
default:
message.error(res.message || 'unknown error');
isSuccess = false;
}
return isSuccess;
};
xhr.error = (err) => {
message.error('The server strayed!');
};