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

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

"Exclusive Mui sx styles will be applied only when a specific breakpoint

As I update my old mui styling to utilize the sx attribute, I've noticed the ability to specify styles for different breakpoints using sx = {{ someCssProp: { xs: ..., md: ... and so on. Prior to this, I had been using theme.breakpoints.only for some ...

Trimming Picture on User's Device

Currently, I am utilizing the jQuery ImgAreaSelect 0.9.10 plugin to crop images that are uploaded by users. The data input format being used is "multipart/form-data". Upon cropping an image with the plugin, it provides me with coordinates in pixels. Howev ...

Having trouble implementing pagination for news-api in Vue.js2?

I am currently working on implementing a basic pagination feature in my Vue component specifically for the newsapi.org API. While my initial API call in the created hook is functioning as expected, I am encountering difficulties navigating to different pa ...

Issue encountered while trying to load electron-tabs module and unable to generate tabs within electron framework

I've recently set up the electron-modules package in order to incorporate tabs within my Electron project. Below are snippets from the package.json, main.js, and index.html files. package.json { "name": "Backoffice", "version": "1.0.0", "descr ...

What is the process for incorporating a new URL into the routes.js file of a preexisting Node.js project that was developed with locomotive?

module.exports = function routes() { this.root('pages#main'); this.match('/status', 'pages#status'); this.resources('paper'); this.resources('tempform'); this.match('/paper/domain', 'pages#n ...

What is the best way to save a parsed JSON value to a variable in Express?

I am currently utilizing the body-parser module to parse incoming JSON objects within a POST request. My goal is to extract and store a specific value from the JSON data into a variable for later database insertion. Below is a fragment of the code: var h ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: He ...

Changing alert variant dynamically with Vue.js and Bootstrap-Vue

As I work on a vue.js project using bootstrap-vue, I came across the following method to display an alert based on the documentation: <b-alert variant="success" show>Success Alert</b-alert> However, my attempt to achieve this is as follows: ...

Is it possible to utilize the node package ssh2 within a web browser environment?

I am working on a project for school where I am creating an SFTP client directly in my browser. I have successfully implemented the node package ssh2 and it works perfectly when running the code in the terminal. I can connect to the server, read directorie ...

Leveraging environmental variables in a Vue.js web application

The article I recently came across discussed how to effectively utilize environment variables in vuejs. Following the instructions, I set up my local .env.local file and also installed dotenv. VUE_APP_AUTH_AUTHORITY = 'http://localhost/auth' I ...

What is the best way to add the ".html" suffix to pages in nuxt.js?

Is it possible to add the ".html" extension to a page address? For instance, changing "test_page" to "test_page.html" ...

WordPress Media Library - Issue with select function not properly updating row index when updating ID

I am currently working on a WordPress blog that includes a custom metabox on the edit page for each post. This metabox contains a table where each row displays an image source selected from the media library. When a new row is added, it is assigned an I ...

Alert: Next.js 13 console error detected

Currently, I am utilizing Next js 13 for the development of a website. However, I have encountered this warning in the console: The resource http://localhost:3000/_next/static/chunks/polyfills.js was preloaded using link preload but not used within a few s ...

Unable to set the active tab using $rootScope

Is there anyone who can assist me with the issue I am currently facing? I have a NavCtrl to manage my active tags, and although I was able to change the active tab when clicking on the menu item, it does not update when clicking on links in the body views. ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

Creating uniform line lengths with a ruler utilizing Fabric.js

I have a div that scrolls horizontally and contains a ruler div and a canvas where I draw horizontal lines of varying lengths. When drawing the lines, I want to ensure they are accurately measured against the ruler using JavaScript and CSS: var canvas = ...

Utilize Typescript/Javascript to utilize the Gmail API for sending emails via email

I am trying to send emails from my application using my Gmail account with Ionic. I have followed tutorials from SitePoint and Google Developers. Here is how I'm initializing the client: client_id: gapiKeys.client_id, discoveryDocs: ["https://www.goo ...

Can anyone provide guidance on how to trigger 3 unique functions in a specific order using JavaScript?

I've been troubleshooting this issue for quite some time, but I just can't seem to figure it out. Here's my dilemma: I have three functions - one to shrink a div, one to reload the div with new data, and one to enlarge the div - all triggere ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...