Search code examples
javascriptrestasync-awaitfetch-apihttp-status-code-401

How can I know I got the 401 error when fetch data?


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.


Solution

  • 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