模板文本表达式的类型"string | null"无效。发送授权时



当我试图执行授权时,Ts-eslint用"Invalid type "string | null" of template literal expression"消息阻止了我。

该值来自本地存储,所以它必须是nullstring,但我也必须将其与Bearer结合。

onMounted(async ()=>{
let myToken = localStorage.getItem('token');

await axios.post(
'http://localhost:3000/getdocuments', 
{headers:{'Authorisation':`Baerer ${myToken}`}}
)
.then((res)=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
})

我认为只有当token存在时才应该调用这个请求

onMounted(async ()=>{
let myToken = localStorage.getItem('token');
if (!myToken) {
console.warn('token is empty');
} else {
await axios.post(
'http://localhost:3000/getdocuments', 
{headers:{'Authorisation':`Baerer ${myToken}`}}
)
.then((res)=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
}
})

对不起,这是晚了,但遇到了同样的错误,只是使用null保护检查修复了它。

获取令牌后,

if (!myToken) {
// Error handle
}

最新更新