You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Axios TypeScript疑难:如何正确处理错误并访问响应头?

解决Axios TypeScript错误:获取429状态码的Retry-After响应头

错误原因

你遇到的TS2723错误,本质是response.headers的类型为RawAxiosResponseHeaders | (RawAxiosResponseHeaders & AxiosHeaders):

  • RawAxiosResponseHeaders是普通的键值对对象,没有get()方法;
  • 只有AxiosHeaders实例才提供get()方法。
    TypeScript无法确定当前headers属于哪种类型,因此认为get()可能不存在,抛出调用风险错误。

正确实现方式

下面提供两种可靠的解决思路,你可以根据需求选择:

思路1:直接通过对象索引访问(兼容两种类型)

普通对象和AxiosHeaders都支持索引访问,只需注意响应头的大小写(后端可能返回Retry-After或小写的retry-after):

axios
    .post<string>('api/refresh-token', credentials)
    .then(response => {
        const token = response.data;
        console.log("Token", token);
        // ...
    })
    .catch((error: Error | AxiosError) => {
        if (axios.isAxiosError(error)) {
            const { response } = error;
            if (response?.status === 429) {
                // 兼容不同大小写的响应头
                const retryAfterText = response.headers['retry-after'] ?? response.headers['Retry-After'];
                // 可选:转成数字类型
                const retryAfter = retryAfterText ? Number(retryAfterText) : null;
                console.log("需要等待秒数:", retryAfter);
            }
        }
    });

思路2:用类型守卫确保安全调用get()方法

先判断headers是否为AxiosHeaders实例,再调用自带的get()方法(该方法会自动处理头名称的大小写,更省心):

import { AxiosHeaders } from 'axios';

axios
    .post<string>('api/refresh-token', credentials)
    .then(response => {
        const token = response.data;
        console.log("Token", token);
        // ...
    })
    .catch((error: Error | AxiosError) => {
        if (axios.isAxiosError(error)) {
            const { response } = error;
            if (response?.status === 429) {
                if (response.headers instanceof AxiosHeaders) {
                    const retryAfterText = response.headers.get('retry-after');
                    const retryAfter = retryAfterText ? parseInt(retryAfterText, 10) : null;
                    console.log("需要等待秒数:", retryAfter);
                } else {
                    // 处理普通对象类型的headers
                    const retryAfterText = response.headers['retry-after'] ?? response.headers['Retry-After'];
                    console.log("需要等待秒数:", retryAfterText);
                }
            }
        }
    });

额外优化建议

  • 无需手动指定response或headers的复杂类型,TypeScript可以自动推断,减少冗余代码;
  • 使用可选链response?.status替代嵌套的if判断,代码更简洁。

内容的提问来源于stack exchange,提问作者eekboom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 10:35:16