fetch header 携带自定义请求头,类型不匹配

2023-01-23 22:09:15 +08:00
 Lukedis
fetch(`${url.baseUrl}${url.user.auth}`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
      //'Authorization': localStorage.getItem('Authorization'),
    },
  }).then((response) => {
    if (response.status == 200) {
      auth = true;
    }
  });

localStorage.getItem('Authorization')type 是 string|null 和headers要求的参数类型不匹配

1085 次点击
所在节点    程序员
5 条回复
lisongeee
2023-01-23 22:20:38 +08:00
```ts
fetch(`${url.baseUrl}${url.user.auth}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('Authorization')!,
},
}).then((response) => {
if (response.status == 200) {
auth = true;
}
});
```
IceBay
2023-01-23 22:38:40 +08:00
'Authorization': `${localStorage.getItem('Authorization')}`,

'Authorization': localStorage.getItem('Authorization') || '',
Lukedis
2023-01-24 08:10:28 +08:00
@lisongeee 在不使用!的情况下,还有哪些解决办法
Track13
2023-01-24 09:05:30 +08:00
不想用!。那就只能提前类型收窄了。
musi
2023-01-24 11:50:31 +08:00
as string

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/910387

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX