类型“AxiosHeaders | Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>”上不存在属性“Authorization”。

10 篇文章 1 订阅

💭💭

✨:在请求拦截器里添加Authorization携带Token报错

💟:东非不开森的主页

💜: 沉下心来💜💜

🌸: 如有错误或不足之处,希望可以指正,非常感谢😉

  • 在请求拦截器里添加Authorization携带Token
 interceptors: {
    requestSuccessFn: (config) => {
      // 每一个请求都自动携带token
      const token = localCache.getCache(LOGIN_TOKEN)
      if (config.headers && token) {
        // 类型缩小
        config.headers.Authorization = 'Bearer ' + token
      }
      return config
    }
  }
  • 发现报错

在这里插入图片描述

  • 查看axios版本:1.2.2

在这里插入图片描述

方法一

在网上查阅资料发现:

1.2.2版本的AxiosHeaders中有这样一个方法可以设置请求头,在headers调用set方法设置一个Authorization属性,查看axios源码发现其有个set方法,可调用该方法设置新的headers的属性名和值

所以我们可以这样写

  • 需要判断set的类型,当其类型为function再调用该方法
    记得Bearer拼接的时候后面有个空格!!!!!
  interceptors: {
    requestSuccessFn: (config) => {
      // 每一个请求都自动携带token
      const token = localCache.getCache(LOGIN_TOKEN)
      if (config.headers &&  typeof config.headers?.set === "function" ) {
          config.headers.set("Authorization", `Bearer ${token}`)
      }
      return config
    }
  }
})

方法2

还可以降版本,将axios卸载,再重新下载1.1.3版本,这样就可以解决报错问题

  yarn remove axios
  yarn add axios@1.1.3

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
类型“((config: AxiosRequestConfig<any>) => AxiosRequestConfig<any>) | undefined”的参数不能赋给类型“((value: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>) | null | undefined”的参数。 不能将类型“(config: AxiosRequestConfig<any>) => AxiosRequestConfig<any>”分配给类型“(value: InternalAxiosRequestConfig<any>) => InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>”。 不能将类型“AxiosRequestConfig<any>”分配给类型“InternalAxiosRequestConfig<any> | Promise<InternalAxiosRequestConfig<any>>”。 不能将类型“AxiosRequestConfig<any>”分配给类型“InternalAxiosRequestConfig<any>”。 属性“headers”的类型不兼容。 不能将类型“AxiosHeaders | (Partial<RawAxiosHeaders & { Accept: AxiosHeaderValue; "Content-Length": AxiosHeaderValue; "User-Agent": AxiosHeaderValue; "Content-Encoding": AxiosHeaderValue; Authorization: AxiosHeaderValue; } & { ...; }> & Partial<...>) | undefined”分配给类型“AxiosRequestHeaders”。 不能将类型“undefined”分配给类型“AxiosRequestHeaders”。 不能将类型“undefined”分配给类型“Partial<RawAxiosHeaders & { Accept: AxiosHeaderValue; "Content-Length": AxiosHeaderValue; "User-Agent": AxiosHeaderValue; "Content-Encoding": AxiosHeaderValue; Authorization: AxiosHeaderValue; } & { ...; }>”。ts(2345) (property) HRequestInterceptors<AxiosResponse<any, any>>.requestInterceptors?: ((config: AxiosRequestConfig<any>) => AxiosRequestConfig<any>) | undefined
07-13

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东非不开森

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值