我使用异步函数来获取数据,我怎么知道我得到了401错误时,获取数据?
代码如下:
async function getBilling(url, id, date) {
let header = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`,
},
}
const response = await fetch(`${url}/billing/${id}/${date}`, header)
const data = await response.json()
if (data.code === 0) {
// setState(...)...
} else {
// ...
}
}
当令牌过期时,我会在浏览器控制台上看到此错误
CORS策略已阻止从源“http://localhost:3000”在“http://...”进行提取的访问:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明响应满足您的需要,请将请求的模式设置为“no-cors”以在禁用CORS的情况下提取资源。
获取http://.../2022年10月网络::错误_失败401
未捕获(承诺中)TypeError:无法获取...
即使我加上这一行
...
const response = await fetch(`${url}/billing/${id}/${date}`, header)
if (!response.ok) {
**console.log(response.status)**
throw new Error(`HTTP error! status: ${response.status}`)
}
...
在浏览器开发模式下,控制台标记中仍无法显示。
所以问题是我怎么知道我得到了401错误?
谢谢你。
1条答案
按热度按时间u0sqgete1#
请考虑使用
try/catch
胶囊。在catch部分,您将获得所有可能的错误。
请阅读更多关于
try/catch
胶囊here的信息