0.0.6 • Published 5 months ago
nti-axios-module v0.0.6
nti-axios-module 使用指南
简介
nti-axios-module
是一个封装了 Axios 的工具类,旨在简化和增强 Axios 请求的管理和处理。通过该封装,你可以方便地添加请求和响应拦截器,处理请求头、修改请求数据,以及在收到响应后进行数据解析和错误处理。
安装
首先,确保你已经安装了 Axios。如果没有,可以通过以下命令进行安装:
npm install axios
然后,将 nti-axios-module
导入到你的项目中:
import NtiItApi from 'nti-axios-module';
使用示例
创建 nti-axios-module 实例
const axiosInstance = new NtiItApi({
// 参考axios配置
axiosConfig: {},
// 参考NProgress配置
progressConfig: {},
_this: { a:1, b:2 },
interceptorsResponse: [
{
sourceCode: `
const beforeRequest = (config) => {
console.log("beforeRequest", config)
return {...config,a:6};
};
`,
type: 3
},
{
sourceCode: `
const afterResponse = (response) => {
console.log("afterResponse", response)
return response;
};
`,
type: 4
},
{
sourceCode: `
const timeoutResponse = (error) => {
console.log("timeoutResponse", error)
return error;
};
`,
type: 5
}
]
});
添加请求拦截器
通过 addRequestInterceptor
方法,你可以添加一个请求拦截器,用于在请求发出之前对请求进行处理。比如,你可以在拦截器中添加请求头信息或修改请求数据。
axiosInstance.addRequestInterceptor((config) => {
// 在请求发出之前对请求进行处理的逻辑
// 可以添加请求头信息、修改请求数据等
return config;
});
添加响应拦截器
使用 addResponseInterceptor
方法添加一个响应拦截器,用于在收到响应后进行处理。你可以在拦截器中进行数据解析、错误处理等操作。
axiosInstance.addResponseInterceptor((response) => {
// 在收到响应后对响应进行处理的逻辑
// 可以解析数据、处理错误等
return response;
});
发起 GET 请求
通过封装后的 Axios 实例,你可以方便地发起 GET 请求。以下是一个获取 JSON 数据的示例:
async function getJson(jsonUrl) {
try {
const res = await axiosInstance.get(jsonUrl);
// 在这里对响应数据进行处理
this.geojson = res.data;
return res.data;
} catch (error) {
// 在这里处理请求错误
console.error('GET request failed:', error);
throw error;
}
}
总结
nti-axios-module
封装了 Axios,提供了便利的方法来管理请求和响应拦截器,使得对请求和响应的处理更加灵活和可控。通过以上示例,你可以轻松地使用 nti-axios-module
发起请求,并在拦截器中加入自定义逻辑,以满足不同场景下的需求。