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

Issues with React - Material UI Menu functionality

I'm encountering an issue with the menu/menu item component from material ui when trying to render it based on a condition. Here is my code snippet... const AddSelectItemButton = () => { return ( <> <Fab ar ...

Utilizing JavaScript to implement conditional if-else statements on CSS properties

I am trying to implement conditions on CSS properties in JavaScript. What is the most efficient approach to achieve this? <html> <head> <title>TOOLTIP USING JAVASCRIPT</title> <style> span{ curso ...

What is the method for showcasing an array using AngularJs in my specific scenario?

I have an array in JavaScript structured like this: var data = [ 2005 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 2006 = [ Jan = [0,1,2,3,5...], Feb = [0,1,2,3,5...], ...more ], 200 ...

What is the best way to implement a dialog box that displays a website within it, all while keeping my SharePoint site running in the background?

For a while now, I've been working on SharePoint Online and trying to troubleshoot an issue without success. That's why I'm considering starting over with a specific section of my SP site from scratch. My current project involves creating a ...

Iterating over an object in a React component

i'm trying to generate an object using iteration like this: opts = [{label:1, value:1}, {label:4, value:4}] the values for this object are coming from an array portArray = [1,4] I'm attempting to do const portArray = [1,4]; return { ...

Having trouble removing a row from Mysql database using Node.js

Recently, I developed a pet shop web application using nodeJS and MySql. Everything was working smoothly until I encountered an issue with deleting pets by their pet_id. Upon attempting to delete using pet_id 'pa04', I received the following erro ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

What sets Fetch apart from ajax and XMLHttpRequest that makes it impressively faster?

Over the past few days, I have been working on optimizing a client table for a project. The table contains over 10k clients, and as a result, it was taking a long time to load. The front-end team had implemented pagination, filters, and reordering, which ...

Issue with Jade not displaying external JSON data

I am struggling with a jade template that is supposed to display all possible solutions from the QPX Express search request: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'RwDOf6H ...

Angular JS displays an error message when the user selects an input field and fails to provide any input

On my wizard steps application, I have implemented Angular JS validation that displays errors when the user enters and removes a character in the input field. However, I am trying to figure out how to show the error message if the user tabs onto the fiel ...

Replicating form fields using jQuery

I have come across many questions similar to mine, but unfortunately none of them address the specific details I am looking for. On a single page, I have multiple forms all structured in the same way: <form> <div class="form-group"> ...

enhancing angular directives with data binding while replacing HTML content inside the compile function

I am currently attempting to develop a directive that will substitute an input field with a custom-made input field. Unfortunately, I am encountering challenges with getting the data binding to function properly, as the model does not display in the direct ...

Validate all JavaScript buttons by binding a click event

I've implemented the JS validation plugin from this source and it's functioning properly. However, it captures all button clicks on the page, including when I click on Back to Home, triggering form validation unnecessarily. I only want the form ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Exploring the process of retrieving outcomes from Node.js within a Knockout ObservableArray

Below is the Node.js code snippet I have: var http = require('http'); var port = process.env.port || 1337; var MovieDB = require('moviedb')('API KEY'); MovieDB.searchMovie({ query: 'Alien' }, function (err, res) { ...

"Material-Table does not have the ability to insert a new row

Just started learning JS and React. I'm attempting to integrate Material-table with an add row button, but encountering issues where the added row is not reflecting. Every time I refresh the page, the rows are reset. I suspect there's a problem w ...

An array in JSON format containing only one element

I am currently working on a project that involves JSON format output. I am in need of some clarity regarding the structure of JSON arrays. Specifically, I'm curious about how to handle fields that allow multiple entries in an array format. In cases wh ...

Turn off choices by utilizing data type attribute values within select2 version 4

I'm attempting to deactivate the options by using the data-type attribute specified for each option in select2. Unfortunately, my attempts have been unsuccessful thus far. In addition, I am encountering this error within the change event handler: ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

jquery to create a fading effect for individual list items

I have a group of items listed, and I would like them to smoothly fade out while the next one fades in seamlessly. Below is the code I've been working on: document.ready(function(){ var list_slideshow = $("#site_slideshow_inner_text"); ...