【问题标题】:How to use Axios interceptor with typescript correctly?如何正确使用带有 typescript 的 Axios 拦截器?
【发布时间】:2022-01-17 15:16:59
【问题描述】:

我已经创建了一个 axios 拦截器:

instance.interceptors.response.use(async (response) => {
    return response.data;
  }, (err) => {
    return Promise.reject(err);
  });

获取response 并返回data 属性。

response 对象属于AxiosResponse<any, any> 类型,data 属性只是AxiosResponse<any, any>.data 类型的数据。

问题是当我使用这个axios客户端时

const instance = axios.create({...});
// ...etc
// add interceptor

然后我做:

customAxiosClient.get().then((data: /* here data is of type AxiosResponse instead of AxiosResponse.data */)

如何解决?

【问题讨论】:

    标签: javascript typescript types axios interceptor


    【解决方案1】:

    您只需在 axios get 方法中指定响应数据类型,如下所示:

    axios.get<never, YourDataType>(...)
    

    【讨论】:

      【解决方案2】:

      Rechu 的回答有效,但我将提供一个替代方案。

      您可以创建一个可重用的函数以使您的 axios 实例保持全局性。我自己在生产中使用它。

      首先,在您的项目中创建一个名为utils/http.ts 的文件夹/文件。接下来,这是我的可重用函数,可将所有内容保存在一个位置。

      import axiosClient from "axios";
      import type { AxiosRequestConfig } from "axios";
      
      /**
       * Creates an initial 'axios' instance with custom settings.
       */
      const instance = axiosClient.create({
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json; charset=utf-8",
        },
      });
      
      /**
       * Handle all responses. It is possible to add handlers
       * for requests, but it is omitted here for brevity.
       */
      instance.interceptors.response.use(
        (res) => res.data,
        (err) => {
          if (err.response) {
            return Promise.reject(err.response.data);
          }
      
          if (err.request) {
            return Promise.reject(err.request);
          }
      
          return Promise.reject(err.message);
        }
      );
      
      /**
       * Replaces main `axios` instance with the custom-one.
       *
       * @param cfg - Axios configuration object.
       * @returns A promise object of a response of the HTTP request with the 'data' object already
       * destructured.
       */
      const axios = <T>(cfg: AxiosRequestConfig) => instance.request<any, T>(cfg);
      
      export default axios;
      

      最后像下面的代码sn-p一样使用它:

      const login = () => {
        const creds = { username: "user", password: "pass" };
      
        axios<User>({ method: "POST", url: "/api/v1/auth/login", data: creds })
          .then((user) => { /* do whatever with user here */ })
          .catch((err) => { /* handle errors */);
      };
      

      它将被输入并准备好立即使用。 axios 函数中的 any 也可以替换为 unknown

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-16
        • 2020-09-19
        • 1970-01-01
        • 2022-10-15
        • 2020-01-19
        • 2019-03-15
        • 2019-06-26
        • 2018-10-31
        相关资源
        最近更新 更多