Unintentional GET request triggered by Axios baseURL

I have encountered a strange issue where defining

axios.defaults.baseURL = baseUrl;
results in an unexpected GET request right after initializing my Vue app. Any assistance would be greatly appreciated!

Below are images showing the code and network requests:

I attempted to follow the suggestions on Setting baseUrl for Axios in Vue js sends out request

Unfortunately, this solution did not work for me

import axios from 'axios';

export const baseUrl = 'http://imfood-core.local';

axios.defaults.baseURL = baseUrl;

axios.interceptors.request.use(function (request) {
  if(request.url !== `/api/login_check`){
    request.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
  }
  return request;
}, function (error) {
  return Promise.reject(error);

});

axios.interceptors.response.use(function (response) {
  axios.defaults.baseURL = baseUrl;
  return response;
}, function (error) {
  if(error.response && error.response.status == 401 && error.config.url !== `${baseUrl}/api/login_check`){
      localStorage.removeItem('token');
      window.location.reload();
      return Promise.reject(error);
  }
  return Promise.reject(error);
});

export default axios;



[1]: https://i.stack.imgur.com/6E9dD.png
[2]: https://i.stack.imgur.com/fnBST.png
[3]: https://i.stack.imgur.com/7sy5z.png

Answer №1

To implement a new axios instance, you can simply create it and then import the file where it is needed.

import axios from 'axios'

const customAxios = axios.create({
  baseURL: 'http://example-api.local'
})

customAxios.interceptors.request.use(function (request) {
  if(request.url !== `/api/login_check`){
    request.headers['Authorization'] = `Bearer ${localStorage.getItem('token')}`
  }
  return request;
}, function (error) {
  return Promise.reject(error);

});

...

export default customAxios

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

Attempting to merge the data from two separate API responses into a single array of objects

I have a current project in which I'm dealing with an object that has three separate arrays of objects. Here's a glimpse of the structure... [ Array 1:[ { key: value} ], Array 2:[ { key: value}, { key: value} ], Array ...

Search through an array of objects that contains nested arrays of objects with various property names and values

I have an Array of objects structured like this: [{ property1: 'test', property2: 'test', filter: [{ fil1: 1, fil2: 2, fil3: 3 }, { fil1: 56, fil2: 3, fil3: 34 ...

Is it possible to utilize the AmMap API for developing an Android application?

I am currently in the process of creating a unique application with HTML, JS, and jQuery Mobile that will feature interactive maps. I have been searching the web for APIs to incorporate interactive maps into my project without using Google Maps APIs when I ...

What is the reason behind JavaScript's restriction on using double comparison operators?

What is the reason behind javaScript not supporting double comparison? For example, in 64 < str.charCodeAt(i) && str.charCodeAt(i)<=77, why is it not possible to simplify it to 64 < str.charCodeAt(i)<=77? ...

Tips for expanding the content of a blogger page to fill the entire frame of the page

Check out this page: . Currently, the video on the page does not fill up the entire screen. Any suggestions for a solution? ...

The connection to MongoDB is failing due to an incorrect URI

I tried setting up mongoDB on my node server and referred to the official MongoDB documentation. Here are the details of my setup: MongoDB version: 4.4.3 Node.js version: v15.7.0 I copied the starter code from MongoDB and here is what I used: const { Mon ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Utilize a function on specific attribute values

I have a function in JavaScript that is designed to convert all relative URLs into absolute URLs. function rel2Abs(_relPath, _base); //_relPath represents the relative path //_base indicates the base URL Now, my objective is to implement this function on ...

JavaScript to enable button functionality for selected items

Currently, I am developing a To-Do List application. Once users input information, it gets displayed in a table format. My objective is to have the ability to select specific items from this table and apply various button functionalities to them such as ma ...

I want to know how to shift a product div both horizontally and vertically as well as save its position in And Store

How can I animate and move a product div horizontally & vertically, and save its position for future visits? I need to move the div with animation in a specific sequence and store the position using PHP. Buttons <button type="button" href ...

What sets apart window.location.href from this.router.url?

I'm curious about the various methods of obtaining the current URL in Angular. For instance: this.router.url My main question is: What advantages does using this.router.url offer over simply using window.location? Could someone kindly provide an exp ...

Custom Typescript type that runs concurrently with the base type is disregarded

Assumption: When creating a custom type that mirrors an existing type, the expectation is for variables assigned to that type to maintain it and not default back to the base type. In the function f provided below, the expected return type should be Dog ins ...

Adjust image size dynamically while keeping the original aspect ratio

Is there a way to scale variable portrait and landscape images dynamically to fit proportionally within a browser window? You can find my current image resizing attempt here: http://jsfiddle.net/6pnCH/4/ I would like the image to be already scaled vertic ...

Implementing jQuery form validator post anti-SPAM verification?

I am facing what seems like a straightforward JavaScript issue, but my knowledge in this area is still limited. Following a successful implementation of basic anti-SPAM feature that asks the user to solve a simple math problem, how can I integrate jQuery& ...

Struggling to Implement Middleware on Router in ExpressJS?

In my application, I have both public and authenticated routes. The isAuthenticated function is used, for example, in a news controller. globalRouter: function (app) { app.use((req, res, next) => { logger.log("Endpoint: ", req.originalUrl); n ...

How can I retrieve information on a logged in Auth0 user from an API?

I'm currently working on a React application that utilizes auth0 in conjunction with an express API server. One issue I'm facing is how to access user information within the API when a secure endpoint is called. While I can retrieve user data on ...

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

Incorrect implementation of Bootstrap CSS in Jade template

Currently, I am leveraging Express to construct a website. However, there seems to be an issue with my jade template not displaying the bootstrap grid system accurately. Despite double-checking that my app path is correctly set through app.use(express.stat ...

Adjust the transparency and add animation effects using React JS

When working on a React project, I encountered an issue where a square would appear under a paragraph when hovered over and disappear when no longer hovered. However, the transition was too abrupt for my liking, so I decided to implement a smoother change ...

How to customize the button color in a Next.js application

Help Needed: Issue with Changing Default Button Color in Next.JS Web Application. The button text color appears as grey on Desktop Google Chrome, but shows up as blue on Mobile Chrome browser. I want to unify the color to be grey on both platforms. Custo ...