对axios进行二次封装,实现更强的复用性和扩展性
axios
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
});
// 请求拦截器
instance.interceptors.request.use(
config => {
// 可以在请求头中添加token等信息
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
response => {
// 可以在这里对响应数据进行处理,例如统一处理错误码等
return response.data;
},
error => {
// 如果请求超时或者网络错误,可以进行请求重试
const config = error.config;
if (!config || !config.retry) return Promise.reject(error);
config.__retryCount = config.__retryCount || 0;
if (config.__retryCount >= config.retry) {
return Promise.reject(error);
}
config.__retryCount += 1;
const backoff = new Promise(resolve => {
setTimeout(() => {
resolve();
}, config.retryDelay || 1);
});
return backoff.then(() => {
return instance(config);
});
}
);
// 创建请求函数
const createRequest = (method, url, data = {}, config = {}) => {
return instance({
url,
method,
data,
...config,
});
};
// 封装get请求
export const get = (url, params = {}, config = {}) => {
return createRequest('get', url, { params, ...config });
};
// 封装post请求
export const post = (url, data = {}, config = {}) => {
return createRequest('post', url, data, config);
};
// 封装put请求
export const put = (url, data = {}, config = {}) => {
return createRequest('put', url, data, config);
};
// 封装delete请求
export const del = (url, params = {}, config = {}) => {
return createRequest('delete', url, { params, ...config });
};
使用示例
import { createRequest } from './axios';
const request = createRequest('get', '/user', { id: 1 });
request.then(res => {
console.log(res);
});
在这个示例中,我们抽象出了一个createRequest
函数,用于创建请求。我们只需要传入请求方法、请求地址、请求数据和请求配置即可创建一个请求。这样我们就可以通过这个函数来封装任何类型的请求,而不需要每一种请求都写一遍封装代码。