Is there a way for me to confirm that I am receiving the 401 error when fetching data?

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.

Answer №1

Consider implementing a try/catch block in your code.

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);
  }
}

The catch section will handle all possible errors that may occur.

  } catch (error) {
    console.log(error);
    // Implement necessary actions for when the endpoint fails.
  }

For more information on using the try/catch block, visit here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we prevent and remove extra whitespace characters such as new lines and line feeds in responseText?

I am troubleshooting an ajax script that is calling a php file. The php file is supposed to echo either "yes" or "no", which I intend to use for logical comparisons. However, when trying to compare the responseText in javascript to check if it matches "y ...

Setting up JW Player with a YouTube Embed URL

Embed link Is it possible to embed a YouTube link in my JW Player without disrupting the design? I have a specific design for the JW Player frame that I need to retain while incorporating the YouTube link. I have searched extensively but haven't foun ...

Leveraging the ReactJS Hook useState for detecting Key press events

As I am in the process of constructing a piano, I want it to showcase certain CSS styles when the user "presses" specific keyboard buttons (via keydown event) - even enabling the simultaneous clicking of multiple different buttons. Once the user releases t ...

Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization: var jsonData = {"Battery Voltage, (A)": {"2017-11-11T00:00:00.000Z":12.3, "2017-11-11T00:01:00.000Z":12.35, ...

Assistance in using jQuery to locate specific div elements is

I am currently working on creating a navigation bar that features icons triggering contextual submenus upon hover. The main idea is that hovering over an icon will display a popup menu or tooltip with additional options, while still allowing the icon itsel ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

Modify a quartet of divs simultaneously

I am currently working on a project that involves 4 input fields, each accompanied by a dropdown element for selecting currency. My goal is to create a JavaScript function that will update all input fields when one of them is changed. For instance, if I s ...

How can I use jQuery to locate all elements that match a specific style within the DOM?

Similar Question: How can I target hidden elements? Selecting multiple elements with CSS display:none property <div class="container"> <p style="display:none">I am hidden</p> <p>I am visible</p> <p>I am also ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

How can I resolve the Error: Element type is invalid?

I am encountering the error message displayed above, and I am uncertain about the cause of this issue. In the code snippet below, I am fetching data from a file named Data.js located in my root folder. When I run the app, I receive the mentioned error mess ...

Is there a way to restrict a user to selecting just one checkbox in a bootstrap checkbox group?

I am having trouble implementing bootstrap checkboxes in my code. I want the user to be able to select only one checkbox at a time, with the others becoming unchecked automatically. Can someone please advise me on what I need to add to my code? Here is a ...

Creating metadata for a node/npm module build

Looking for a solution to output JSON with build date and updated minor version number using grunt and requirejs for our application. It seems like this would be a common requirement. Any existing tools that can achieve this? ...

Splitting Code in React Components using Webpack within a Ruby on Rails Application

I'm currently integrating ReactJS components into my Rails application using the Webpack gem. However, I am facing an issue where the React components are only being loaded in specific areas within the layout of the Rails application. This results in ...

Does anyone have insight on which JavaScript library is being utilized in this context?

While perusing an interesting article, I came across an image that caught my attention. Clicking on it revealed a unique way to view the full size. I am curious if anyone knows which JavaScript library was used for this effect. You can find the article her ...

Utilizing the Vuetify pagination feature in your project

I am in need of some guidance regarding the configuration of vuetify pagination. I have a card component that I loop through, but I also want to implement pagination around it. Any insights on where to start would be greatly appreciated? <v-pagination ...

The issue I am facing is that the map function is not functioning correctly when I click

I am currently working on a project in ReactJs that includes a sidebar with dropdown menu functionality. Desired Outcome When I click on an option in the sidebar that has a submenu, it should display that submenu and close upon another click. Curr ...

Jquery doesn't immediately hide an element after the first click.TabPage.getSelection().extentNode rectangular_HTML

I'm experiencing a peculiar issue with an event listener $(document).on('click', '.suggested-location-item', function(event) { event.preventDefault(); $('#IDsuggestedLocationsList').html(''); $(&apo ...

React Redux Loading progress bar for seamless navigation within React Router

Currently, I am working on adding a loading bar similar to the one used by Github. My goal is to have it start loading when a user clicks on another page and finish once the page has fully loaded. In order to achieve this, I am utilizing material-ui and t ...

What is the proper way to implement v-model for a custom component within the Vue render function?

Below is the code that I am working with: ... var label_key_map = { a: "1", b: "2", c: "3", d: "4" } render: (h) => { var form_data = {} for (let key in label_key_map) { var form_item = h( 'FormItem', {props: {prop: key}}, ...