axios handle 401

Solutions on MaxInterview for axios handle 401 by the best coders in the world

showing results for - "axios handle 401"
Amanda
18 Jun 2020
1axios.interceptors.response.use(response => {
2   return response;
3}, error => {
4  if (error.response.status === 401) {
5   //place your reentry code
6  }
7  return error;
8});
Chrissy
15 Jan 2018
1import axios from 'axios';
2import config from '../../configuration.json';
3import qs from 'qs';
4
5const baseURL = config['baseUrl_local'];
6let authTokenRequest;
7
8/**
9  * @description axios instance for ajax requests
10*/ 
11
12var client = axios.create({
13baseURL: baseURL,
14headers: {
15    appID: 8,
16    version: "1.1.0",
17    empID: localStorage.getItem('empID'),
18    token: localStorage.getItem('accessToken')
19}
20});
21
22/**
23 * @description this method calls a requestNewToken method to issue a 
24 new token to the client
25*/ 
26
27 function getAuthToken() {
28   if (!authTokenRequest) {
29   authTokenRequest = requestNewToken();
30   authTokenRequest.then(resetAuthTokenRequest, resetAuthTokenRequest);
31 }
32 return authTokenRequest;
33 }
34
35/**
36  * @description this method requests the server to issue a new token, 
37  the server response is updated in local storage accessToken
38*/ 
39
40function requestNewToken() {
41  var newToken = request({
42  method: "post",
43  url: '/sign-in',
44  data:  qs.stringify({
45         "userName":localStorage.getItem('userName'),
46         "password":localStorage.getItem('password')
47         })  
48  }).then((res)=>{
49  if(res.status == "success"){
50    localStorage.setItem('accessToken',res.data.accessToken);
51    //if featureArray is present in response object, update the 
52    featureArray in local storage
53    if(res.data.features){
54      localStorage.setItem(
55      'featureArray',
56     JSON.stringify(res.data.features));
57    }
58    client = axios.create({
59     baseURL: baseURL,
60     headers: {
61          appID: 8,
62          version: "1.1.0",
63          empID: localStorage.getItem('empID'),
64          token: localStorage.getItem('accessToken')
65      }
66   });
67 } else {
68  window.location = "/logout";
69 }
70});
71 return newToken;
72}
73
74function resetAuthTokenRequest() {
75  authTokenRequest = null;
76 }
77
78/**
79  * @description if any of the API gets 401 status code, this method 
80   calls getAuthToken method to renew accessToken
81  * updates the error configuration and retries all failed requests 
82  again
83*/ 
84
85client.interceptors.response.use(undefined, err => {
86  const error = err.response;
87  // if error is 401 
88  if (error.status===401 && error.config && 
89  !error.config.__isRetryRequest) {
90  // request for a new token
91  return getAuthToken().then(response => {
92   // update the error config with new token
93   error.config.__isRetryRequest = true;
94   error.config.headers.token= localStorage.getItem("accessToken");
95   return client(error.config);
96  });
97 } 
98});
99
100/**
101 * @description wrapper for making ajax requests
102 * @param {object} object with method,url,data etc.
103*/ 
104
105const request = function(options) {
106  const onSuccess = function(response) {
107    return response.data;
108  }
109 const onError = function(error) {
110  //console.error('Request Failed:', error.config);
111   if (error.response) {
112  //console.error('Status:',  error.response.status);
113  //console.error('Data:',    error.response.data);
114  //console.error('Headers:', error.response.headers);
115  } else {
116  console.error('Error Message:', error.message);
117  }
118 return Promise.reject(error.response || error.message);
119 }
120
121return client(options)
122        .then(onSuccess)
123        .catch(onError);
124        options
125}
126
127export default request;
128