【问题标题】:Why `config.headers` in interceptor is possibly undefined为什么拦截器中的 config.headers 可能未定义
【发布时间】:2021-11-30 02:35:30
【问题描述】:

我是 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?: 记录

【问题讨论】:

    标签: node.js typescript http axios interceptor


    【解决方案1】:

    错误告诉你 Axios 为其 API 定义 TypeScript 类型的方式,config 可能是 undefined 当你的拦截器函数被调用时。 (它在 TypeScript 操场上也是 looks that way。)interceptors documentation 没有说任何话,这似乎很奇怪。

    如果您确定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;
    });
    

    【讨论】:

      猜你喜欢
      • 2019-08-07
      • 1970-01-01
      • 2018-09-27
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      相关资源
      最近更新 更多