Update the default base URL configuration for Axios

My axios configuration looks like this:

const configAxios = {
  baseURL: 'http://127.0.0.1:8000/api',
  timeout: 30000,
};

Vue.prototype.$axios = axios.create(configAxios)

When making a call inside my component, I use the following syntax:

this.$axios.get('items').then()..

Although the above code works fine, I'm looking to dynamically change the baseURL without impacting the global base URL. This way, I can conveniently use it in my component without specifying the API endpoint every time.

I've attempted the following approach:

this.$axios.baseURL = "http://127.0.0.1:8000";
this.$axios.get().. //still uses the api endpoint

What would be the best way to achieve this?

Answer №1

Here's a clever workaround I discovered to avoid hardcoding URLs for specific requests. It's a simple yet effective solution.

In order to add 'api' to my baseURL dynamically, I initially set my default baseURL as,

axios.defaults.baseURL = '/api/';

Then, when making a specific request where I don't want 'api' in the URL, after setting the method and URL explicitly, I adjust the baseURL like this:

axios({
    method:'post',
    url:'logout',
    baseURL: '/',
   })
   .then(response => {
      window.location.reload();
   })
   .catch(error => {
       console.log(error);
   });

Answer №2

Instead of

try using this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

It's preferable to specify the method like

this.$axios({ method: 'get', url: 'items', baseURL: 'http://new-url.com' })
to avoid any confusion.

For more information on request configuration, visit: https://github.com/axios/axios#request-config

Answer №3

  1. To set up your API endpoint, make sure to create the following files if they do not already exist: .env.development and .env.production. In these files, add your API endpoint like this:
    VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
  2. In the main.js file, include the following line after your imports:
    axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT

By doing this, you will replace Axios's default base URL with the specific API endpoint for each build mode. If you need a specific baseURL for individual requests, you can specify it as follows:

this.$axios({ url: 'items', baseURL: 'http://new-url.com' })

Answer №4

If you're still looking for assistance:

To modify the Axios base URL, simply adjust it in the specific location where it is needed.

updateAxiosBaseUrl(){
 axios.defaults.baseURL = http://wwww.newexample.com
 axios({
   url:'/dogs' //=>  http://wwww.newexample.com/dogs
 })
}

This change will only affect the base URL in this particular instance.

Please be aware that altering the base URL here will not impact the main.js configuration.

Answer №5

According to information found in the documentation for axios, there are two key parameters to take note of: baseURL and url

baseURL should be set as the base URL that will be used for all requests, while url represents the specific endpoint being targeted. For example, setting baseURL as http://127.0.0.1:8000 allows you to make requests to /url

// `url` specifies the server URL to send the request to
 url: '/user',

 // `baseURL` will be appended to `url` unless `url` is a complete URL itself.
 // It can be useful to define `baseURL` for an axios instance when working with relative URLs.
 baseURL: 'https://some-domain.com/api/',

Answer №6

you can also implement this method (specifically for nuxt and vue)

this.$axios.defaults.baseURL = 'http://example.com/example'

I successfully used this approach to set a custom baseURL for a single request

async fetchDataFromServer({ commit }, payload) {
    commit('setLoadingStatus', true)
    try {
      const page = payload.page || 1
      const sort = payload.sort || 'published_at'

      this.$axios.defaults.baseURL = 'http://example.com/example'
     
      const { data } = await this.$axios.get(`/example`)

      commit('updateStateWithData', data)
    } catch (error) {
      throw new Error(error)
    } finally {
      commit('setLoadingStatus', false)
    }
  },

Answer №7

One possible solution is...

axios.get("https://custom-url", {baseURL:"")

By doing this, you can replace the baseURL set in the axios interceptor with a different one for just this particular request.

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

Vue component not reflecting updated value from axios response

I am struggling to update the temp object after making an axios call. Any assistance would be greatly appreciated. This is the entire code snippet. I have implemented this component in a Vue application. Vue and components are new to me, so any guidance ...

Guide on exporting a dynamically imported class instance using ES6 modules in NodeJS

Currently, I am engrossed in a book on NodeJS that illustrates a simple web application example. In this example, the prerequisite is to have various data store classes housed in their respective modules and dynamically selecting the data store by configur ...

Tips for properly updating node.js within an ionic framework application

Currently, I am working on a project that utilizes vue / vuetify and I am trying to merge it into an Ionic project. The original project is functioning well with vue version 3.4, whereas the Ionic project is using Vue version 3.3, which is not suitable for ...

Unexpected "<" and dual output in jade include seem to defy explanation

i am currently redesigning my website to incorporate dynamic includes. These includes are pre-rendered on the server and then passed to res.render() however, I am encountering unexpected occurrences of < and > on the page, along with the issue of th ...

Pattern matching for a string with numerous repetitions using Regular Expressions

There's a [tree] and a cat and a [dog] and a [car] too. I am looking to find the words inside each set of square brackets. The resulting array will be tree, dog, car My attempt at using match(/\[(.*)\]/g) didn't work as expected. It ...

Having difficulties redirecting with the button's onclick function

I'm struggling to redirect users to another page using a button (assuming the hostname is localhost:8000) $('#getFruit').attr('onclick', window.location.host + '/getFruit/banana') <script src="https://cdnjs.cloudfl ...

"How to set the header in AngularJS when opening a new window with a GET request URL

Can anyone provide guidance on setting headers and opening a URL (https://www.example.com) in a new window without including sensitive authentication information in the URL parameters? I am working with AngularJS for this task. I have searched through exi ...

Issues with fundamental JavaScript client-side code

As a newcomer to the world of javascript and jQuery, I am diving into my first experiment with javascript. My initial focus has been on changing questions by clicking next or previous buttons. The goal is to create a dynamic quiz webpage that updates quest ...

Why isn't changing the property of a Sequelize instance having any effect?

While I've successfully used the standard instance syntax in the past, I'm facing a challenge with updating an instance retrieved from the database in this specific section of my code. ... const userInstance = await db.models.Users.findOne({wher ...

Ways to invoke a controller function from a window listener function

Is there a way to trigger the close function from window.onbeforeunload even when closing the app through 'right click' -> 'close window'? It seems that this.close() is not working in this scenario, possibly due to scope issues. The ...

The browser is opting to download the HTML file rather than displaying it

Recently, I set up a server using Node.JS express where I specified the location of an HTML file in the public folder. app.use(express.static(__dirname + '/public')); app.listen(8080); In previous projects, this setup worked seamlessly. However ...

struggling to navigate the request to a different HTML page from the controller using AngularJS

Having a situation where I need Page A to render Page B with the values entered on Page A upon submission. Page A is connected to controller A, and when the click event triggers, the Spring controller renders Page B. The problem I'm encountering is t ...

Displaying default value in select dropdown using v-model

I am working on a Vue selectbox with an initial v-model value, and I want to display its value on the selectbox. However, I am unsure of how to accomplish this. Any assistance would be greatly appreciated. new Vue({ el: "#demo", data() { return ...

`I am unable to insert an image into PrimeReact`

I am struggling to integrate images into the dashboard using primereact. Despite placing my photo folder in the public directory and entering the correct photo path, the image is not displaying on the page. I have attempted numerous methods but have been ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...

Using jQuery to Extract HTML Content from a JSON Object

I'm completely lost on what I'm doing incorrectly, but the JSON string I have looks like this: jsonp443489({"content":"<!DOCTYPE html><html><head><title>Title</title></head><body><p>Hello World< ...

Articles related to Express.js - encountering issues when attempting to read properties from a null object

I'm trying to display related articles based on categories using Mongoose for querying data from MongoDB. However, when I attempt the code below, I encounter an error message stating "TypeError: Cannot read properties of null (reading 'category& ...

Attempting to link two JavaScript files, however, only one of them is functioning correctly

I'm currently experiencing an issue with my HTML page that involves calling two JS files for two different image sliders on the same website page. One slider works perfectly fine while the other does not. I'm confused as to whether it's perm ...

Creating a Dynamic Clear Button for a Text Area in Angular

Working on my Angular application, I have implemented a form with a textarea element. My goal is to incorporate a clear button inside the textarea element that should: Appear only when the textarea is focused Disappear when the textarea is out of focus ( ...

What is the best way to calculate the percentage of a quantity within the <td> tag?

I am trying to calculate the percentage of quantity per day by summing up all quantities and then dividing each quantity by the total sum. However, when I combine these calculations in my HTML code using distributed.Quantity, I end up with a NaN value. How ...