When using an async function to fetch data, how can one determine if a 401 error occurred during the data retrieval process?
The code example is as follows:
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 {
// ...
}
}
When the token expires, the following error may appear in the browser console
Access to fetch at 'http://...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET http://.../2022-10 net::ERR_FAILED 401
Uncaught (in promise) TypeError: Failed to fetch at ...
Even after adding the following lines of code:
...
const response = await fetch(`${url}/billing/${id}/${date}`, header)
if (!response.ok) {
**console.log(response.status)**
throw new Error(`HTTP error! status: ${response.status}`)
}
...
The 401 error still does not show up in the browser developer console.
The main issue here is how to properly identify and handle the 401 error.
Thank you.