我是打字稿的新手。我有一个我使用的标题的值,它工作得很好。我尝试将它分成另一个可以调用的函数,但是它不起作用。
这是没有被调用的代码
var headers: any = "";
try {
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
} catch (err) {
console.log(err);
}
axios
.get("https://localhost:", { getHeader })
当使用标头作为参数执行 .get 时,此工作文件。但是当我试图把它变成一个函数时。
export function getHeader () {
let headers: Record<string, string | null> = {}; // this line
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
return headers
}
它抛出一个错误。
Type 'Record<string, string | null>' is not assignable to type 'AxiosRequestHeaders'.
“字符串”索引签名不兼容。键入'字符串 | null' 不可分配给类型 'string | 号码 | 布尔值'。类型 'null' 不能分配给类型 'string | 号码 | 布尔值'。
我怎样才能让它作为一个函数工作?
编辑:try catch 块不正确。解决它。
编辑:从带有错误消息的评论中添加了更新的代码。
您正在尝试将整个函数传递给 axios 配置,而不是使用该函数的结果。
试试这个:
axios.get("https://localhost:", { headers: getHeader() })
另一方面,您的getHeader
功能存在小问题 -
Record
而不是any
string
?改为使用空对象const
orlet
代替var
export function getHeader () {
let headers: Record<string, string> = {}; // this line
const token = getCookie('XSRF-TOKEN');
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-XSRF-TOKEN': token
};
} catch (err) {
console.log(err);
}
return headers
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句