iT邦幫忙

0

透過 typeScript 封裝 axios, config header 型別定義

  • 分享至 

  • xImage

想請問一下,我今天客製化了一個axios
https://ithelp.ithome.com.tw/upload/images/20230526/20129747K4O3bPb3LH.png
不過在 config.header 部分,看似因為屬性的類型不符合 AxiosRequestHeaders 引起的。
https://ithelp.ithome.com.tw/upload/images/20230526/20129747j0O7qvVTyK.png

有上網查了相關資源,不過還是一樣噴錯,請問這個問題要怎麼解決?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
小哈片刻
iT邦研究生 5 級 ‧ 2023-05-26 22:16:23

有可能是axios版本不合,如果要快速解決的話,可以試試把config看成any。

axios.interceptors.request.use(
    (config: any) => {
        ...
    }
)
0
pblaten
iT邦新手 3 級 ‧ 2023-06-01 15:53:29

據我所知,axios這個套件1.2.x的版本有一些潛在的ts問題。
我之前在封裝時,在AxiosRequestConfig也出現類似的問題。
當時的解決方式也是透過降版處理。
根據網站一網站二,遇到的issues應該跟你的差不多,討論也有分享他們的封裝處理方式。

下面是axios 1.2.2時,我曾封裝過的request interceptors,可以參考看看:

import axios, { AxiosRequestConfig, AxiosHeaders } from 'axios';
apiInstance_globalApiInstance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    config.headers = { ...config.headers } as AxiosHeaders;
    config.headers.set('Authorization', token);
    ...set你的header資料
    return config;
  },
  function (error) {
    // 進行錯誤處理
    console.log('_global_api__REQUEST', error);
    return Promise.reject(error);
  }
);
janlin002 iT邦好手 1 級 ‧ 2023-06-01 16:36:52 檢舉

謝謝你!我研究看看~~

我要發表回答

立即登入回答