Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token is always used in subsequent requests.

const customAxios = (axios as any).create({
  baseURL: mainConfig.apiBaseUrl,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Update token if it's present in the response.
customAxios.interceptors.response.use(response => {
  if (response.headers.token !== undefined) {
    response.config.headers.token = response.headers.token;
  }
  return response;
});

Answer №1

Here, the setting for further requests cannot be done like this.

It is recommended to utilize globalStorage or any other type of storage mechanism to store this token securely.

import Store from "Store";

const request = (axios as any).create({
  baseURL: mainConfig.apiBaseUrl,
  headers: {
    'Content-Type': 'application/json',
    'Authorization': Store.token
  },
});

// Utilize the latest token from the store
axios.interceptors.request.use(function (config) {
    const {token} = Store;
    config.headers.Authorization = token;
    return config;
  }, function (error) {
    return Promise.reject(error);
  });

// Update the token in the store
request.interceptors.response.use(response => {
  const {token} = response.headers;
  if (token) {
    Store.setToken(token);
  }
  return response;
}

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

Updating your feed dynamically using Ajax in Rails 4.0: A step-by-step guide

I'm currently working on implementing ajax functionality for a sample app inspired by Michael Heart's book. I've set up a feed model controller, which is similar to microposts in his book. I'm attempting to use ajax for posting feeds, b ...

Using React's Ref to handle conditional rendering and handling the case when

I am facing an issue with my React ref animationRef being null when I conditionally render an element. It works perfectly fine outside of the condition, but not within it. Is there a way to ensure that the ref has a value even when conditionally renderin ...

Partially translucent electron window

Is there a way in Electron to create a view similar to the finder in macOS, where the sidebar is opaque and the main content is not? https://i.stack.imgur.com/UKXg2.jpg I am aware of how to make an entire window opaque, but I'm unsure if it's p ...

"Image Reactor: Unleashing the Power

I'm struggling to understand why my relative path image loading isn't functioning correctly. The assets are located within the src folder in my working directory, but for some reason, they're not displaying as expected. When I directly impo ...

Tips on accessing dictionaries with multiple values in JavaScript

I am struggling with a particular dictionary in my code: {1:['a&b','b-c','c-d'],2:['e orf ','f-k-p','g']} My goal is to print the key and values from this dictionary. However, the code I att ...

Unable to locate the specified environment variable in the current nest

Currently, I am referring to the official documentation on the NestJs website that provides a guide on using config files: https://docs.nestjs.com/techniques/configuration Below is the code snippet I am working with: app.module import { Module } from &ap ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

Node scripts and node bins are causing errors in Vue.js when running npm

While attempting to run my Vue project with the command npm run serve I encountered an error message that read: [email protected] serve /home/numan/Desktop/vue-getting-started/07-accessing-data/begin/vue-heroes vue-cli-service serve sh: 1: vue- ...

The combination of Node.js module.exports and shorthand ternary operators for conditional statements

Can you explain the purpose of this line 'undefined' != typeof User ? User : module.exports and why is everything enclosed within (function(){})? I am having trouble understanding its significance. This code snippet is extracted from a library f ...

Analyzing Data for Distributed / External Pages

Our team is currently exploring options for tracking metrics on content we produce for external pages. We are considering various approaches such as creating our own JavaScript, using a tracking pixel, or adapting Google Analytics to fit our needs. We wou ...

Experiencing issues with references while trying to import tone.js

I am facing an issue with my express.js server setup on my Mac. I am trying to incorporate Tone.js, which can be found at , following the provided instructions. npm install tone To integrate Tone.js successfully: import * as Tone from 'tone' Ho ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

What advantages does incorporating "function() 'use strict'" into each individual file provide?

As I dive into revamping an older AngularJS 1.3 project, one striking observation is the consistent pattern of starting each AngularJS code file with: (function () { 'use strict'; angular.module('app').factory('Employees', ...

Exploring the transition from JavaScript to jQuery

Currently, I have set up an ajax request in combination with JavaScript to fetch data from an external file. The code looks like this: const ajaxRequest = new XMLHttpRequest(); const handleResponse = function() { if (ajaxRequest.readyState === 4) { ...

Starting object arrays in Angular 6 using ES6

As someone who is just starting out with javascript, I have encountered a challenge with a nested class structure. Specifically, I am looking to initialize an array of EventDate objects and assign it to 'this.dates' within the CustomerEvents cons ...

Integrating Constant Contact API into a Next.js application

I'm trying to integrate the Constant Contact API into my Next.js application. I've looked through the documentation, but it only provides examples for PHP and Java. How can I effectively use the authentication flow and create an app on the dashbo ...

Unlock the potential of displaying similar object values side by side in JavaScript, React, and ES6 - here's how!

Currently, I am dealing with an object called segregatedData which is being passed as props. Among its several properties, we are interested in segregatedData.type1. This particular property is essentially an array of strings similar to this: ['water& ...

Display all information associated with the class that matches the clicked ID

Can anyone help me with a Jquery question? I am trying to display all data with the same class when I click on it. I have created a list of clickable items. When I click on an item, the corresponding data should be shown. However, the code I wrote is not ...

Have Vue props been set to null?

Currently, I have a component within my vue.js application that looks like this: export default { props: ['forums'], methods: { increment(forum, index) { ForumService.increment(forum) .then(() => { ...