2

I use async function to fetch data, How can I know I got the 401 error when fetch data?

code like this:

    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 is expired, I will get this error on 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 when I add this line

...
    const response = await fetch(`${url}/billing/${id}/${date}`, header)
    if (!response.ok) {
            **console.log(response.status)**
            throw new Error(`HTTP error! status: ${response.status}`)
    }
    ...

still can not show on browser develop mode in console tag.

So the problem is How can I know I got the 401 error?

Thank you.

Kaneki21
  • 1,323
  • 2
  • 4
  • 22
MOLLY
  • 409
  • 2
  • 12
  • 2
    Are you asking how to handle errors? If so, you need to catch the error you are throwing if the response is not ok. Consider using `try/catch` blocks. – ivanatias Oct 25 '22 at 04:12
  • 2
    console.log(response) Here you will get a property status that give you status code. https://bobbyhadz.com/blog/javascript-get-response-status-code-fetch#:~:text=To%20get%20the%20status%20code,500%20for%20a%20server%20error. – Arifur Rahaman Oct 25 '22 at 04:38
  • Agree with @ivanatias, consider using `try/catch` and you will handle all possible errors. – Josué Ayala Oct 25 '22 at 05:38
  • @ArifurRahaman I added console.log(response) after this line ` const response = await fetch(`${url}/billing/${id}/${date}`, header)`, But still no show in browser's console – MOLLY Oct 25 '22 at 05:44
  • Oh I got it. If the server doesn't respond at all, or you encounter a CORS error or misspell the URL, you will get a network error, which would run the catch function and the status property would not be populated as it isn't a server HTTP response. – MOLLY Oct 25 '22 at 05:49

1 Answers1

3

Please consider using a try/catch capsule.

async function getBilling(url, id, date) {
  try {
    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();

    // setState(...)...
  } catch (error) {
    console.log(error);
  }
}

In the catch section, you will get all possible errors.

  } catch (error) {
    console.log(error);
    // Handle all actions when the endpoint has failed. 
  }

Please read more about try/catch capsule here

Josué Ayala
  • 285
  • 1
  • 12