Axios ошибка 401

I got it working with following code

import axios from 'axios';
import config from '../../configuration.json';
import qs from 'qs';

const baseURL = config['baseUrl_local'];
let authTokenRequest;

/**
  * @description axios instance for ajax requests
*/ 

var client = axios.create({
baseURL: baseURL,
headers: {
    appID: 8,
    version: "1.1.0",
    empID: localStorage.getItem('empID'),
    token: localStorage.getItem('accessToken')
}
});

/**
 * @description this method calls a requestNewToken method to issue a 
 new token to the client
*/ 

 function getAuthToken() {
   if (!authTokenRequest) {
   authTokenRequest = requestNewToken();
   authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
 }
 return authTokenRequest;
 }

/**
  * @description this method requests the server to issue a new token, 
  the server response is updated in local storage accessToken
*/ 

function requestNewToken() {
  var newToken = request({
  method: "post",
  url: '/sign-in',
  data:  qs.stringify({
         "userName":localStorage.getItem('userName'),
         "password":localStorage.getItem('password')
         })  
  }).then((res)=>{
  if(res.status == "success"){
    localStorage.setItem('accessToken',res.data.accessToken);
    //if featureArray is present in response object, update the 
    featureArray in local storage
    if(res.data.features){
      localStorage.setItem(
      'featureArray',
     JSON.stringify(res.data.features));
    }
    client = axios.create({
     baseURL: baseURL,
     headers: {
          appID: 8,
          version: "1.1.0",
          empID: localStorage.getItem('empID'),
          token: localStorage.getItem('accessToken')
      }
   });
 } else {
  window.location = "/logout";
 }
});
 return newToken;
}

function resetAuthTokenRequest() {
  authTokenRequest = null;
 }

/**
  * @description if any of the API gets 401 status code, this method 
   calls getAuthToken method to renew accessToken
  * updates the error configuration and retries all failed requests 
  again
*/ 

client.interceptors.response.use(undefined, err => {
  const error = err.response;
  // if error is 401 
  if (error.status===401 && error.config && 
  !error.config.__isRetryRequest) {
  // request for a new token
  return getAuthToken().then(response => {
   // update the error config with new token
   error.config.__isRetryRequest = true;
   error.config.headers.token= localStorage.getItem("accessToken");
   return client(error.config);
  });
 } 
});

/**
 * @description wrapper for making ajax requests
 * @param {object} object with method,url,data etc.
*/ 

const request = function(options) {
  const onSuccess = function(response) {
    return response.data;
  }
 const onError = function(error) {
  //console.error('Request Failed:', error.config);
   if (error.response) {
  //console.error('Status:',  error.response.status);
  //console.error('Data:',    error.response.data);
  //console.error('Headers:', error.response.headers);
  } else {
  console.error('Error Message:', error.message);
  }
 return Promise.reject(error.response || error.message);
 }

return client(options)
        .then(onSuccess)
        .catch(onError);
        options
}

export default request;

[EDIT] Its 2019, Here is yet another implementation for the same. The above solution is great but does not work well with multiple failed request, in turn it calls getToken with the updated token as well.

 import axios from "axios";

 /* @internal */
 import config from "../config";
 import TokenService from "./token_service";

class Request {
    constructor() {
        this.baseURL = config.baseUrl;
        this.isRefreshing = false;
        this.failedRequests = [];
        this.tokenService = new TokenService();
        this.client = axios.create({
            baseURL: config.apiServerBaseUrl,
            headers: {
               clientSecret: this.clientSecret,
            },
        });
        this.beforeRequest = this.beforeRequest.bind(this);
        this.onRequestFailure = this.onRequestFailure.bind(this);
        this.processQueue = this.processQueue.bind(this);
        this.client.interceptors.request.use(this.beforeRequest);
        this.client.interceptors.response.use(this.onRequestSuccess, 
this.onRequestFailure);
}

beforeRequest(request) {
    const token = TokenService.getAccessToken();
    request.headers.Authorization = `Token ${token}`;
    return request;
}

static onRequestSuccess(response) {
    return response.data;
}

async onRequestFailure(err) {
    const { response } = err;
    if (response.status === 401 && err && err.config && !err.config.__isRetryRequest) {
        if (this.isRefreshing) {
            try {
                const token = await new Promise((resolve, reject) => {
                    this.failedRequests.push({ resolve, reject });
                });
                err.config.headers.Authorization = `Bearer ${token}`;
                return this.client(err.config);
            }
            catch (e) {
                return e;
            }
        }
        this.isRefreshing = true;
        err.config.__isRetryRequest = true;
        return new Promise((resolve, reject) => {
            this.tokenService.refreshAccessToken().then((token) => {
                this.tokenService.setAccessToken(token);
                err.config.headers.Authorization = `Bearer ${token}`;
                this.isRefreshing = false;
                this.processQueue(null, token);
                resolve(this.client(err.config));
            }).catch((e) => {
                this.processQueue(e, null);
                reject(err.response);
            });
        });
    }
    throw response;
}

processQueue(error, token = null) {
    this.failedRequests.forEach((prom) => {
        if (error) {
            prom.reject(error);
        } else {
            prom.resolve(token);
        }
       });
        this.failedRequests = [];
    }

}

const request = new Request();

export default request.client;

@Chathula

i can’t handle the 401 Unauthorized error. but before that axios always console.log() the POST 401 (Unauthorized) error. i don’t want to see that. how to fix it.

alt tag

This is the error i got as result.. i use Next.js / React

Error: Request failed with status code 401
    at createError (eval at evalScript (http://localhost:3000/_next/next-dev.bundle.js:36657:9), <anonymous>:971:16)
    at settle (eval at evalScript (http://localhost:3000/_next/next-dev.bundle.js:36657:9), <anonymous>:2964:13)
    at XMLHttpRequest.handleLoad (eval at evalScript (http://localhost:3000/_next/next-dev.bundle.js:36657:9), <anonymous>:813:8)

@rubennorte

This is a regular HTTP response, not an issue in Axios.

You should check the documentation of the API you’re using in order to solve your problem.

@lephuhai

Hi @Chathula, I also research about to handle this. You can using validateStatus config in this case.

See about this here !

@Chathula

@Vietworm I’l give a try!

Thank you!!

@achilleskineur

validateStatus work Fine

Thank you

@Bilal112

getting this error how can solve it

@guastallaigor

@Bilal112 Did you try catching the error with error.response.data.error? See example:

this.$http.$post('url', user).then((response) => {
  //
})
.catch((error) => {
  this.showErrors(error.response.data.error)
})

Btw, i’m using Nuxtjs and axios module.

AlexanderSoliar, Thuku, lukeddy, bandaranaike, Crazyde, ferbs89, mblanco98, pelcasandra, gloryer, imamrobani, and 3 more reacted with thumbs up emoji
erdemoflaz reacted with heart emoji

@AlokSuman

login = () => {
axios.post(«https://192.168.0.10:8244/authenticateUser/1.0.0/outh», {
headers: {
«Content-Type»: «application/json»,
«Accept»: «application/json»,
«Authorization»: «Bearer df498c83-1c88-308e-a224-5408dd67bb7f»
},
data: {
«authKey»: «YWRtaW46YWRtaW4=»,
«clientId»: «dWZkSHJnd05ZUjNDTXVpa3NDakJ4anNvaWZZYTpqcks5ZmFjZjBBbHRLVzY1UFVNZjl0OWRSck1h»,
«username»: «KPFACTORS/Alok.Suman»,
«passkey»: «Alok@123»
}
})
.then(response => response.json())
.then(response => console.log(«hi» + response))
.catch(err => console.log(«error » + err));
};

@MuhammetALAPAN

Some APIs have property like «apikey» and you should indicate that property when you are using axios.

You should look your API’s doc for properties and also you can use Postman for indicate your url, header, params etc. easily.

@rubennorte, @lephuhai, @AlokSuman thank you :)

componentDidMount () {
    axios
      .get("https://api.hurriyet.com.tr/v1/newsphotogalleries?$top=20", {
        params : {"$top": "20"},
        headers : {"apikey": "b21x5457136cxa5fdafc7v1x645526vb"}})
        .then(news => console.log(news))
}

@waqaramjad

i received some different response in postman while the same thing i get an error in axios

@Bilal112

i received some different response in postman while the same thing i get an
Hi
What is the error
waqar

@waqaramjad

@Bilal112

that’s my error
Request failed with status code 401 at createError (E:React NativeEximAppEximAppnode_modulesaxioslibcorecreateError.js:16) at settle (E:React NativeEximAppEximAppnode_modulesaxioslibcoresettle.js:17) at XMLHttpRequest.handleLoad

while with postman that my response
{ "error": "Unauthorised" }

@vidorifaldy

@Bilal112

that’s my error
Request failed with status code 401 at createError (E:React NativeEximAppEximAppnode_modulesaxioslibcorecreateError.js:16) at settle (E:React NativeEximAppEximAppnode_modulesaxioslibcoresettle.js:17) at XMLHttpRequest.handleLoad

while with postman that my response
{ "error": "Unauthorised" }

check this

validateStatus: (status: number) => status >= 200 && status < 300,

line 39, axios just get status in range 200-300
if you change status on backend, you can get your response like in postmant

hope this can help you guys

@ashish9342

Added debugger to check the object, so this is how the error object looks like.
Refer screenshot. Right side(under scope)

Screenshot 2020-02-17 at 4 39 40 PM

@axios
axios

locked and limited conversation to collaborators

May 22, 2020

To use Axios interceptors to handle 401 API errors and refresh access/JSON web tokens(JWTs) tokens in TypeScript/Javascript, you can do the following:

  1. Import the axios library and create an instance of the axios object:
import axios from 'axios';

const instance = axios.create();

Enter fullscreen mode

Exit fullscreen mode

  1. Define a function to refresh the access token using a refresh token:
function refreshAccessToken(refreshToken: string): Promise<string> {
  // Send a request to the server to refresh the access token using the refresh token
  return axios
    .post('/refresh-token', { refreshToken })
    .then((response) => response.data.accessToken);
}

Enter fullscreen mode

Exit fullscreen mode

  1. Add an interceptor to the instance object to handle 401 errors. In the interceptor, check for a 401 error, and if one is found, refresh the access token using the refresh token and retry the original request:
instance.interceptors.response.use(
  (response) => response,
  (error) => {
    const originalRequest = error.config;

    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      const refreshToken = // Get the refresh token from storage

      return refreshAccessToken(refreshToken).then((accessToken) => {
        // Replace the access token in the original request config
        originalRequest.headers['Authorization'] = `Bearer ${accessToken}`;
        return instance(originalRequest);
      });
    }

    return Promise.reject(error);
  }
);

Enter fullscreen mode

Exit fullscreen mode

With this in place, whenever an Axios request returns a 401 error, the interceptor will automatically refresh the access token and retry the original request.

It’s important to note, however, that this example is just a rough outline of how to use Axios interceptors to handle 401 errors and refresh access tokens in TypeScript. You will need to handle additional edge cases in a real-world application and implement proper error handling.

For more information, be sure to refer to Axios’ official documentation on interceptors.

Hello I have a problem That I don’t know how to solve, I am using an API to get the list of movies, my URLs are set right, I verified them multiple times

Here is my ReactJS code to use :

class App extends Component {
   constructor(props) {
     super(props);
   }

   componentWillMount() {
    axios.get(`${API_END_POINT}${POPULAR_MOVIES_URL}&${POPULAR_MOVIES_URL}`);
   }

// my render method here thet return a simple element

}

But I get this error on my console :

Error: Request failed with status code 401

Is there a solution for this ?

Any help would be much appreciated.

Axios is currently the most widely used http request toolkit. When handling errors, we can quickly implement error handling based on the interceptors provided by the framework.

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    // Handling of basic errors such as 4xx/5xx
    alert('Global error handling')

    return Promise.reject(error); 
});

However, the response interceptor provided by axios is global. If we want to error handle a specific request, the situation is a little complicated.

If there is a voting interface, because the back end limits the number of votes, we need to handle it separately when the voting exceeds the limit; The response returned is as follows:

HTTP/1.0 429 Too Many Requests

{"error_code":4291011,"message":"Number of votes exceeded today"}

Maybe for some front-end students, the processing method is to directly add corresponding condition judgment to the response Interceptor:

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    if (error.response.status == 429) {
        if (error.response.data.error_code == 4291011) {
            // Handle voting errors individually
        } else if (error.response.data.error_code == 4291011) {
            // The number of work tickets is abnormal. You need to pass the sliding verification code first
        }
    }

    // Handling other basic errors such as 4xx/5xx
    return Promise.reject(error); 
});

But there are many problems in doing so

  • With the increase of various error codes, the interceptor needs to deal with more and more situations, and finally is full of a large number of if else
  • The specific error code should be put together with the specific code that initiates the request to facilitate viewing and expansion and positioning

So we can move the error handling logic to the calling code, as follows:

axios.post('/vote/1').then(function (response) {
    // success
}).catch(function (error) {
    let code = error.response.data.error_code
    if (code == 4291011) {
        alert('Voting overrun')
    } elseif (code == 4030001) {
        alert('The number of work tickets is abnormal. You need to pass the sliding verification code first')
    }
});

However, there is another problem. Because the code of the axios interceptor will be executed before the catch, when the catch is executed, the code of the response interceptor has actually been executed. Therefore, global error handling — > voting overrun will pop up one after another.

Obviously, this is not what we want. We hope that when we handle errors individually, we will first perform specific business error handling, and finally perform global error handling.

As follows:

  • In this case, when there is no catch, we want the global error to handle the request error.
axios.post('/vote/1').then(function (response) {
    // success
})

This is feasible by default, and no additional preparation is required.

  • When we use catch, we want to handle custom errors first, and then global errors.
axios.post('/vote/1').then(function (response) {
    // success
}).catch(error => {
    // custom error 
})

However, this is not feasible at present. Let’s see axios request After the method source code, I learned that the framework did not provide me with the corresponding hook when initiating the request; So when Promise executes catch, the code in the interceptor must have been executed.

We can only rely on the config provided by axios to complete this feature, as shown below:

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    error.globalErrorProcess = function () {
        switch (this.response.status) {
            case 401: // Handling basic 401 errors
                break;
            case 404: // Handling basic 404 errors
                break;
            case 403: // Handling basic 403 errors
                break;
                      // Handling other basic errors such as 4xx/5xx
        }

        return Promise.reject(this);
    };

    if(error.config.hasOwnProperty('catch') && error.config.catch == true) {
        return Promise.reject(error);
    }

    return error.globalErrorProcess()
});

We define a global error handler and assign it to the globalErrorProcess method of the error object. Then judge whether catch is enabled for the current request config. If it is enabled, no error processing will be performed by default and the caller will be responsible for it; Otherwise, it is handled with a global error.

When using, if you need to customize the error capture, you can display and pass a config. The API of the corresponding request method is as follows:

  • axios.request(config)
  • axios.get(url[, config])
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])
axios.post('https://api.github.com/xxx', null, {catch: true}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    let code = error.response.data.error_code

    if (code == 4291011) {
        // There are too many votes today, and the QR code of the following official account is displayed
    } else if (code == 4031011) {
        // Voting period not allowed,
    } else if (code == 4291012) {
        // The number of work tickets is abnormal. You need to pass the sliding verification code first
    }

    return error.globalErrorProcesser()
});

Finally, don’t forget to call global error handling, otherwise you won’t be lazy about other exception handling.

If you have a better plan, please leave a message and discuss it together.

Reference & Discussion

  • Global error handling using axios interceptor · GitHub
  • javascript — How to manage axios errors globally or from one point — Stack Overflow
  • A Laravel exception context solution | Laravel China Community

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Awg 253 whirlpool ошибки
  • Awg 252 whirlpool коды ошибок
  • Awe 6515 whirlpool коды ошибок
  • Awe 2322 коды ошибок

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии