我想为来自axios的所有http调用全局设置axios拦截器。我们的http调用包装在一个类型记录类Foo中。
import Axios, axios from 'axios';
import { configAxios } from 'config';
class Foo {
Foo() {
configureAxios();
}
public callAxios() {
axios.request() // send the http request
}
}
default export new Foo();在config.ts中,它定义了拦截器配置:
export default function configAxios() {
Axios.interceptors.request.use(req => { // config request });
Axios.interceptors.response.use(res => { // config response });
}但没有截获任何请求或答复。我遗漏了什么?
发布于 2022-08-17 03:21:03
首先,不要在类构造函数中配置拦截器。这将在每次创建该类的实例时添加重复项。
我建议创建一个特定的Axios实例,以便将拦截器绑定到它.
// client.ts
import axios from "axios";
const client = axios.create({
baseURL: "https://example.com" // just an example
});
// Some example interceptors that add properties to the standard request config
// and read it in the response.
interface MyCustomConfig extends AxiosRequestConfig {
myMagicProperty?: number;
}
api.interceptors.request.use<MyCustomConfig>((config) => ({
...config,
myMagicProperty: performance.now(),
}), null, { synchronous: true });
api.interceptors.response.use((res) => {
console.log((res.config as MyCustomConfig).myMagicProperty);
return res;
});
export default client;通过这种方式,您仍然可以访问默认实例(或创建全新的实例),而不需要拦截器,这可以方便地进行身份验证或令牌刷新请求。它还确保您的实例只创建一次并配置一次。
现在,只需在类中使用此实例即可。
import client from "./client";
class Foo {
public callAxios() {
client.request() // send the http request
}
}
default export new Foo();https://stackoverflow.com/questions/73382473
复制相似问题