我的应用程序中有一个 api 客户端,带有一些拦截器:
const api = new OpenAPIClientAxios({...})
const client = api.initSync()
client.interceptors.request.use(...)
client.interceptors.response.use(...)
我想编写一个请求拦截器来检查本地存储中的某些数据。如果数据存在,我想根本不发出请求,而是简单地用本地存储数据进行响应。
这可能吗?还是我滥用了拦截器?
拦截器只能用于操作请求和响应的配置。不幸的是,您无法完全绕过他们的请求。
Axios 确实提供了
adapter
配置,其中...
允许自定义处理请求
// mock localStorage
const localStorage = {s:{},setItem(k,v){this.s[k]=v},getItem(k){return this.s[k]??null}};
// mock OpenAPI client
const client = /* api.initSync() */ axios.create({ baseURL: "https://echo.zuplo.io/" });
const wrapper = axios.create({
adapter: (config) => {
const data = JSON.parse(localStorage.getItem("data"));
if (data) {
// return a valid response
return Promise.resolve({
data,
config,
status: 200,
});
}
// otherwise pass-through to the real client
delete config.adapter;
return client(config);
}
});
(async () => {
// with no data present
console.log("no local data", (await wrapper.get("/")).data);
// with local data
localStorage.setItem("data", JSON.stringify({ foo: "FOO" }));
console.log("with local data", (await wrapper.get("/")).data);
})();
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/axios.min.js"></script>