首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用express全局配置axios拦截器?

如何使用express全局配置axios拦截器?
EN

Stack Overflow用户
提问于 2022-08-17 03:11:48
回答 1查看 808关注 0票数 0

我想为来自axios的所有http调用全局设置axios拦截器。我们的http调用包装在一个类型记录类Foo中。

代码语言:javascript
复制
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中,它定义了拦截器配置:

代码语言:javascript
复制
export default function configAxios() {
     Axios.interceptors.request.use(req => { // config request });
     Axios.interceptors.response.use(res => { // config response });
}

但没有截获任何请求或答复。我遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-17 03:21:03

首先,不要在类构造函数中配置拦截器。这将在每次创建该类的实例时添加重复项。

我建议创建一个特定的Axios实例,以便将拦截器绑定到它.

代码语言:javascript
复制
// 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;

通过这种方式,您仍然可以访问默认实例(或创建全新的实例),而不需要拦截器,这可以方便地进行身份验证或令牌刷新请求。它还确保您的实例只创建一次并配置一次。

现在,只需在类中使用此实例即可。

代码语言:javascript
复制
import client from "./client";

class Foo {
  public callAxios() {
    client.request() // send the http request
  }
}

default export new Foo();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73382473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档