在使用Axios和Typescript编写Next.js的代码时,可能会遇到一个常见的问题:headers类型问题。具体表现为,当尝试传递headers参数给Axios时,TypeScript会显示类型错误。
例如,以下代码段:
const headers = {
Authorization: `Bearer ${token}`
};
axios.get('/api/data', { headers }).then(response => {
console.log(response.data);
});
会导致以下类型错误:
Argument of type '{ headers: { Authorization: string; }; }' is not assignable to parameter of type 'AxiosRequestConfig'
为了解决这个问题,我们需要将headers定义为AxiosRequestConfig中的一部分,如下所示:
const headers:AxiosRequestConfig = {
headers: {
Authorization: `Bearer ${token}`
}
};
axios.get('/api/data', headers).then(response => {
console.log(response.data);
});
通过这种方式,我们把headers参数嵌套在AxiosRequestConfig中,解决了TypeScript类型错误问题。