node.js - 为什么拦截器中的 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>
解决方案
该错误告诉您 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;
});
推荐阅读
- flutter - 如何在 Flutter 图表中显示来自刻度选择的数据?
- code-signing - 覆盖已由 Microsoft 签名的依赖文件的证书签名有什么缺点吗?
- android - 未经检查的演员表:列表
? 列出 - intellij-idea - IntelliJ:不要运行 git hooks
- ms-access - 基于另一个字段的条件字段
- javascript - 用于大型 html 的 DOMParser
- python - 用于算法交易的 Python 脚本使用
- amazon-web-services - 是否可以从 us-east-1 以外的区域创建 AWS QuickSight 命名空间?
- product - 产品图片未显示
- r - 在 R 中以长格式数据按组创建新变量