1

I am using axios to make apis calls in react. If there is no token provided or token got expired server sends the 401 status. I want to check that status on reactjs side.

But if i check err object in catch the status field is null.

Here is the code

try {
      MyService.getIntet(reqBody);
    } catch (err) {
        handleUnAuthorizedResponse(err);
    }

on the error this shows this type of info. enter image description here

In the service

import axios from "axios";

and the function

static getIntent(reqBody) {
    const url = `${this.intentionBaseUrl}/process`;
    const options = {
      headers: {
        "Content-Type": "application/json"
      },
    };
    return axios
      .post(url, reqBody, options)
      .then((res) => res.data)
  }

HOw can i handle 401?

Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

0

The error you've logged does not have a status because the request ended in a Network Error, which is not a 401. You could check if it's a CORS problem, or else.

Otherwise, to manage the 401, seems good to use the handleUnAuthorizedResponse passing the error that should contain:

const err = {
 ..., // other things like the request etc
 code: 'ERR_BAD_REQUEST',
 response: {
  status: 401, // status code
  statusText: 'Unauthorized',
  data: {} // data if the server sends some, like error messages, etc
 }
}
DharmanBot
  • 1,066
  • 2
  • 6
  • 10
  • server is working, if i paas the valid token the request is served with response, if the token is missing server explictly sets the status 401 – Sunil Garg May 17 '22 at 14:34