如何在ReactJS + TypeScript中正确设置Axios拦截器

v64noz0r  于 2023-04-11  发布在  React
关注(0)|答案(1)|浏览(173)

我主要使用JS和React,但我选择使用Typescript,但由于某些原因,旋转请求拦截器示例一直给我这个错误:

src/utils/services/axios.service.ts:16:8
TS2322: Type '{ 'Content-Type': string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeaderValue | undefined; }' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ 'Content-Type': string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeaderValue | undefined; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.
    14 |   let headers = {...config.headers, 'Content-Type': 'application/json', Authorization: `JWT ${token}`};
    15 |   if(TokenHelpers.checkIfLoggedIn()) config.headers = headers;
  > 16 |   else config.headers = {...config.headers, 'Content-Type': 'application/json'};
       |        ^^^^^^^^^^^^^^
    17 |   return config;
    18 | }, error => Promise.reject(error));

这是我的axios.service.ts文件

import axios from "axios";
import CacheHelper from "../helpers/cacheHelper";
import TokenHelpers from "../helpers/tokenHelpers";
import CookieHelper from "../helpers/cookieHelper";
import {Configs, GeneralAppInfo} from "../helpers/constants";

const instance = axios.create({
baseURL: GeneralAppInfo.BASE_URL,
});

instance.interceptors.request.use(config =\> {
let token = TokenHelpers.getToken();
let headers = {...config.headers, 'Content-Type': 'application/json', Authorization: `JWT ${token}`};
if(TokenHelpers.checkIfLoggedIn()) config.headers = headers;
else config.headers = {...config.headers, 'Content-Type': 'application/json'};
return config;
}, error =\> Promise.reject(error));

如果我能了解如何解决这个问题,我会很高兴。

sh7euo9m

sh7euo9m1#

引用要更新的字段作为对象解构对我来说很有效:

const instance = axios.create({baseURL: GeneralAppInfo.BASE_URL});

instance.interceptors.request.use(config => {
  let token = TokenHelpers.getToken(), 
       authorization = `JWT ${token}`, 
       contentType = 'application/json';

  if(TokenHelpers.checkIfLoggedIn()) {
    config.headers['Authorization'] = authorization;
    config.headers['Content-Type'] = contentType;
  } else config.headers['Content-Type'] = contentType;
  return config;
}, error => Promise.reject(error));

相关问题