首页 > 解决方案 > 为什么拦截器中的 config.headers 可能未定义

问题描述

我是nodejs的新手,所以我很难解决一些问题,提前谢谢你。所以这是我的.../src/http/index.ts文件

import axios from 'axios'

export const API_URL = `http://localhost:5000/api`

const $api = axios.create({
    withCredentials: true,
    baseURL: API_URL
})

$api.interceptors.request.use((config) => {
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`
    return config
})

export default $api 

config.headers在这里加了下划线, ts 告诉我

Object is possibly 'undefined'.  TS2532
12 |
13 | $api.interceptors.request.use((config) => {
14 |     config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`
   |     ^
15 |     return config
16 | })
17 |

我只是想了这么久,无法理解问题所在

AxiosRequestConfig.headers?: Record<string, string>

标签: node.jstypescripthttpaxiosinterceptor

解决方案


该错误告诉您 Axios 为其 API 定义其 TypeScript 类型的方式config可能是undefined在调用您的拦截器函数时。(而且它在 TypeScript 操场上看起来也是这样。)拦截器文档并没有说明任何一种方式,这看起来很奇怪。

如果您确定config参数永远不会是,则undefined可以包含一个断言,说明:

$api.interceptors.request.use((config) => {
    if (!config?.headers) {
        throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
    }
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`;
    return config;
});

如果您不正确,那将导致运行时错误。

如果您不确定,可以根据需要创建配置:

$api.interceptors.request.use((config) => {
    if (!config) {
        config = {};
    }
    if (!config.headers) {
        config.headers = {};
    }
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`;
    return config;
});

推荐阅读