Create a global base URL variable within the Axios plugin for Vue

As I work on my Vue.js project, I've successfully implemented a plugin for Axios following the guidelines provided here. This allows Axios to be utilized globally within the project. The key snippets of code in my project are as follows:

in src/plugins/axios.js -

import axios from 'axios';

export default {
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$axios', { value: axios });
  }
}

in src/main.js -

import axios from './plugins/axios';
Vue.use(axios);

new Vue({
  render: h => h(App),
  created() {
    console.log(this.$axios ? 'axios plugin works' : 'axios plugin does not work');
  }
}).$mount('#app');

When checking the console, the message "axios plugin works" confirms that everything is functioning correctly up to this point.

Within a file that utilizes Axios, there are hardcoded URLs present. Here's an excerpt showcasing a method from the file:
src/forms/official-scenarios.vue -

export default {
    data() {
        return {
                errors: [],
                officialScenarios: []                
        }
    },
    methods: {
        getOfficialScenarios() {
            this.$axios
            .get('https://localhost/myapp/api/scenariolog')
            .then(response => {
                this.officialScenarios = response.data;
            })
            .catch(error => {
                this.errors.push(error);
            });
        }
    },
    mounted: function () {
        this.getOfficialScenarios(); 
    },
}

I'm interested in establishing a global base URL for https://localhost/myapp/api and referencing it in all methods utilizing this.$axios. How can this base URL be defined? And what would the implementation look like in official-scenarios.vue?

Answer №1

To configure the base URL within the axios instance, you can do so by incorporating the following code snippet:

// Defining the base URL
axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';

Answer №2

I made some adjustments to the code in src/plugins/axios.js:

import axios from 'axios';

const instance = axios.create({
    baseURL: 'myapp/api/'
});

export default {
  install: function(Vue) {
    Object.defineProperty(Vue.prototype, '$axios', { value: instance });
  }
}

By leveraging Axios' support for relative paths, I removed the unnecessary part of the baseURL string, which was originally set as `https://localhost/`.

Subsequently, the implementation within the getOfficialScenarios() method located in src/forms/official-scenarios.vue transformed into this:

getOfficialScenarios() {
    this.$axios
    .get('scenariolog')
    .then(response => {
        this.officialScenarios = response.data;
    })
    .catch(error => {
        this.errors.push(error);
    });
}

Answer №3

To easily access environment variables in Vue, consider using a .env file and declaring them as global variables either in Vue or Vuex store. For example, you can define API_URL as process.env.API_URL and then access it using this.$store.state.API_URL (or getter).

For more information, refer to this link.

Another approach is to create an axios instance for making HTTP requests.

Learn how to do this by checking out this resource.

Best regards!

Answer №4

If you are working with Vue 3 and come across this, I have made a slight modification to the accepted solution above:

import axios from 'axios'

const instance = axios.create({
    baseURL: 'myapp/api/'
});

export default Vue => Vue.provide('$axios', instance)

You can also customize your URL based on the environment by using environment variables. For example, instead of hardcoding 'myapp/api/', you can utilize environment variables like this (especially useful when using vite):

import.meta.env.VITE_AXIOS_BASE_URL

I hope this information proves useful for you :)

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

Error code E11000 is thrown due to a duplicate key in a Node.js application

Whenever I input data on the webpage, it syncs correctly with the database. However, when I attempt to fill out the same form again, an error occurs: { "code": 11000, "index": 0, "errmsg": "E11000 duplicate key error collection: test.creates i ...

What is the best way to conceal a bootstrap directive tooltip in Vue.js for mobile users?

Currently, I'm tackling a project with Vuejs and Laravel. There's a tooltip directive incorporated that relies on Bootstrap's functionality. Check it out below: window.Vue.directive("tooltip", function(el, binding) { // console ...

Retrieving the output of JavaScript code in C#

How can I retrieve the value from a window.prompt() alert box in my C# Code Behind file? I know it's a simple line of JavaScript, but I want to execute it and get the result within my Code Behind. Whether it's done through a <script> tag in ...

AngularJS single-page application with model-view-controller style designs

Hey there, I'm relatively new to AngularJS and currently on a steep learning curve. I've been working on developing an AngularJS SPA and have grasped the basics. I'm using ngRoute for routing and have put together a basic application framew ...

Angular - automated pagination functionality without requiring user input

I apologize for the poorly worded title. Context In my static display angular app, I am not incorporating any user interactions and most actions are time-based. The page loads, and after a specific amount of time determined by certain elements, it reload ...

Updating Text in Textarea upon Selection Change

Need assistance with updating the content of a textarea based on a select option change. Below is an example of my code: <tr><td>Template:</td><td> <select t name="template" onChange = "setTemplate();"> <option ...

Using Vue.js to alter the CSS class property

I am exploring Vue.js and looking to modify a CSS class property. Here is the HTML code utilizing the specified class: <div class="customTimer"></div> Here is the corresponding CSS code: .customTimer { width: 100%; height: 1 ...

Achieve the identical outcome of the code in jQuery using React.js

Hey there! I'm currently exploring how to achieve similar results using React JS. I realize my request might seem a bit trivial, but I'm in the process of understanding how JavaScript and React JS can be connected in practical projects. Feel fr ...

What is the best way to call an API and display the retrieved value in a div upon the page loading?

Seeking help to retrieve data from an API and display the response within a div tag. I know it's possible with jQuery, but I prefer a different approach. Currently, the page is loading blank. <body> <div id="OnLoad"></div& ...

Using arguments within Vue to conditionally bind events

When attempting to conditionally bind an event method in the template, I encounter some issues. In the template: <div class="survey-card__option radio" :class="data.column ? data.column : ''" v-for='(option, index) ...

Exploring Typescript ENUMs

I need to save a list of alpha-numeric options as an ENUM in Typescript. Here is an example list: 1.134/2394 x 3-xyz 2.123/234 y 3-ery 3.345/99 t 4-red 4.4.1hv 3 secondary 5.2.51hv 3 secondary 6.1.61hv 3 secondary If anyone has thoughts on how to ...

Vue 3 Render Function: Placing App Inside Root Element Using innerHTML Instead of Overwriting it

Is there a way to replace the root element with the rendered app in Vue 3 instead of appending it inside the root element? We are currently migrating from Vue 2 to Vue 3 and need the app to be rendered without the root element. The app is quite large and ...

Tips on automatically populating a textbox without the need for a button click

I am currently using the following code: <input type="text" value="<?php echo empty($this->session->store['actual_info']['actual_total_marketing_budget']) ? '' : $this->session->store['actual_info' ...

What is the best way to identify different directives within the same $scope?

When it comes to calling directive functions from controllers, I follow this approach: function myControllerFunction = function () { $scope.highlight(); } The highlight() function is defined within the directive itself. But what if there are two dif ...

What is the process for creating unit tests for a method that utilizes the @Transaction() decorator?

I am currently using NestJS 6 and TypeORM to interact with a MySQL database. While attempting to write unit tests for a method that utilizes the @Transaction() and @TransactionManager() decorators, I encountered the following error message: ConnectionNotF ...

Component does not display dynamically created DOM elements

I have a function that creates dynamic DOM elements like this: const arrMarkup = []; const getMarkup = () => { if (true) { arrMarkup.push( <Accordion expanded={expanded === cust.name} onChange={handleChange(cust.name)}> ...

What steps can I take to ensure that the v-main element occupies at least 70% of the viewport height in Vuetify?

As a newcomer to Vuetify, I am still learning the ropes. One thing I've noticed is that <v-main> automatically expands to fill the space between <v-app-bar> and <v-footer>, taking up the entire viewport height. My concern arises wh ...

When creating a FlipCard, you may encounter the error message "The object may be null" while using the document.querySelector() method

Having trouble creating a flipcard on Next.js with tsx. The querySelector('.cardflipper') doesn't seem to locate the object and I keep getting this error: "Possibly the object is null". Does anyone know a solution to help my method recognize ...

Tips for positioning text alongside ICONS using CSS

Is there a way to align the text in the second row with the text in the first line? Here is the URL for my website: https://stgbusiness.wpengine.com/ And here is the code: <img src="https://stgbusiness.wpengine.com/wp-content/uploads/2021/10/modu ...

Issues with AngularJS edit functionality for records not functioning as expected

I have implemented a feature on my page where users can add objects to an array. These objects are then displayed on the page along with links for editing each item in the array. Each added item is assigned a primary key, allowing users to edit it later e ...