为什么' 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下划线显示了

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,>

这个错误告诉你Axios为它的API定义TypeScript类型的方式,当你的拦截器函数被调用时,config可能是undefined。(在TypeScript playground中也是如此。)拦截器的文档并没有说明任何问题,这看起来很奇怪。

如果你是肯定如果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;
});

最新更新