Use the .env variable to assign the baseURL in VueAxios

I am currently utilizing a standard Vue starter webpack template with VueAxios integration. My aim is to set up axios configuration using .env variables specifically when building with the dev command. I have everything structured within the /config/index.js:

const devEnv = require('./dev.env')
module.exports = {
...
    host: devEnv.host || 'localhost',
    port: devEnv.port || 8080,
...
}

Subsequently, I establish my host and port in dev.env.js located in the same directory, and it operates seamlessly.

const dotenv = require('dotenv').config({path: '../.env'})

let host = process.env.VUE_HOST;
let port = +process.env.VUE_PORT;

module.exports = merge(prodEnv, {
    NODE_ENV: '"development"',
    host,
    port
})

However, the issue arises when trying to access the host value within src/main.js of my Vue application.

When attempting it like this, an error message is returned stating:

vue is not defined

import axios from 'axios'
import VueAxios from 'vue-axios'
...
Vue.use(VueAxios, axios)
Vue.axios.defaults.baseURL = `http://${process.env.host}:${process.env.port}`;

While the port functions correctly, the host triggers an error.

Answer №1

Update for Simplified Vue CLI 3 Setup

To easily set up your base URL in Vue CLI 3, simply add VUE_APP_BASE_URL to your project's .env file. This will allow you to access it using:

process.env.VUE_APP_BASE_URL

For a more efficient solution, consider configuring a development server as well by following the official guide.


Prior Solution Method

The previous method required a few extra steps:

  • In your webpack.dev.conf.js file, create a special variable within the plugins section instead of directly using process.env.

    new webpack.DefinePlugin({
        'process.env': require('../config/dev.env'),  // Avoid using this for baseURL
        'baseURL': JSON.stringify(`http://${HOST || config.dev.host}:${PORT || config.dev.port}`)
    }),
    
  • In your \src\main.js file, define and use the baseURL like this:

    if (typeof baseURL !== 'undefined')
    {
        Vue.axios.defaults.baseURL = baseURL;
    }
    

Answer №2

I found the answer above to be helpful, but I would like to make a slight amendment. It is necessary to define a constant in the /src/main.js file.

For example:

const baseURL = 'http://localhost:8080';
if (typeof baseURL !== 'undefined') {
  Vue.axios.defaults.baseURL = baseURL;
}

There is no need to add any code in the webpack.dev.conf.js file. However, this solution may only apply to my specific problem.

The issue I am facing can be found here: Dynamic host in axios

Answer №3

It's important to remember that only certain variables, such as NODE_ENV, BASE_URL, and any variable beginning with VUE_APP_, will be included in the client bundle through webpack.DefinePlugin.

An example of a valid variable name would be VUE_APP_HOST.

For more information, please visit this link: https://cli.vuejs.org/guide/mode-and-env.html#environment-variables

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

What is the best way to delete an item from a React array state?

In my Firebase database, I have an array stored under the root branch called Rooms. Within the app, there is a state named rooms which is also an array. I successfully set it up so that when a user enters a new room name and submits it, it gets added to th ...

Inspect the HTTP response status code within the Axios promise catch block in VueJs

Recently started using VueJS. I have created the code below to fetch data from the Controller with axios: SubmitForm: function () { axios({ method: 'post', url: '/Home/SubmitedForm', data: { "Fields": this.$data } ...

Inject SCSS variables into Typescript in Vue 2 Using Vue-cli 5

When working on my Vue 2 project (created using the Vue-cli v4), I successfully imported variables from my SCSS file into my typescript (.vue files) without any issues. I had the :export { ... } in my SCSS file _variables.scss, along with shims.scss.d.ts ...

Check if the data is in JSON format or a string before executing any logic based on that information

Is it possible to identify whether the server has returned JSON data or just a string? If so, how can I parse the JSON and display each element in a loop, or simply display the string. I envision achieving something like this: Send a POST request wit ...

"Troubiling with preact-cli and Babel/TypeScript configurations for enabling correct functionality of Symbol.iterator and spread syntax

Within my codebase, there exists a function named range that is responsible for generating ranges. The implementation of this function is outlined below: export const range = (min: number, max: number) => { // ... return { // ... ...

"Switching from dispatch to emit in VueJS: A step-by-step

I need a way to communicate from a child component to its parent in VueJS without using Vuex. I find Vuex too complex for my current level of understanding with VueJS. My project involves single file components. Here is the code snippet for the child comp ...

Experiencing a 404 error after attempting to access an endpoint following a successful MSAL Azure AD

Incorporating the UserAgentApplication.loginPopup function to authenticate users on our Azure AD has been a challenge as we transition from an ASP.NET MVC application to a Vue.js front end and ASP.NET 'API' backend. The goal is to pass the access ...

Issue with AngularJS $broadcast not functioning when initializing

In the controller, there is HTML button code that attempts to call a specific function on click: <button ng-click="vm.openpopup()" ng-if="!vm.data.length" uib-tooltip="Add Business Value Chain" class="btn btn-default `enter code h ...

angularslideables retro animation

I'm currently using the AngularSlideables library to toggle a modal within my Ionic project. You can check out a functional example in this fiddle: http://jsfiddle.net/3sVz8/19/ However, I am facing an issue where the initial height is set to 100% i ...

Running a Python script from Node.js may seem daunting at first, but with

I'm working on a node.js API where I need to run a python script. Here's my directory structure: Nodejs_application index.js Python_application script1.py The python script just contains print("Hello World"). Here's the code sni ...

Transmit a collection of images in JSON format from a Node.js server

Greetings, fellow listeners and callers! :-) As a newcomer to the world of nodejs and javascript, I am finding it challenging to grasp the event and callback model. My objective is to generate and return a JSON array containing information about photos ( ...

"Clicking on one item in the Bootstrap submenu doesn't close the other items,

I have this Javascript code snippet that deals with expanding and collapsing submenu items: <script type="text/javascript> jQuery(function(){ jQuery(".dropdown-menu > li > a.trigger").on("click",function(e){ var current ...

Codepen fails to function properly after being uploaded to a server

I have encountered an issue with my code on CodePen. After exporting it as a .zip file and attempting to run it on a local server, it failed to work. I am unsure of the exact reason behind this. I made sure to include all the necessary dependencies in the ...

Encountering an error when trying to call useI18n in Vue 3? Remember to always include it at the beginning of the `setup` function to

I am facing a persistent issue with the useI18n function that I cannot seem to resolve. No matter what I try, I keep encountering an error message in my console: Uncaught SyntaxError: Must be called at the top of a setup function Upon inspecting the sta ...

Exploring the number of checked checkboxes within a dynamic list using Ionic 3 and Angular

I'm developing an application where I need to display a dynamic number of checkboxes and determine how many are checked before enabling a button. Some suggestions recommend using myCheckbox.isChecked() to check each checkbox individually, but since ...

EffortlessDrop.js and anchors

Currently using EasyDropDown.js to style a select element, which creates a modern dropdown menu using jQuery. I'm curious if it's possible to include a hyperlink in one of the select options. Here's an example of what I'm trying to ach ...

using Javascript to eliminate necessary tags from concealed tabs

My goal is to dynamically remove the required tag from fields in hidden tabs when a tab is clicked using JavaScript. The presence of the required tag on unused fields causes issues with form submission, preventing data insertion into the database. Here&apo ...

function to trigger lazy loading with jQuery and callback function

Currently, I am triggering a function when lazyload renders an image, which is working well. However, the issue arises when I need to access $(this) within the function. Is there a way to pass this data to the function? You can view the code in action on ...

How can you write a parameterless function in Ramda using a point-free style?

Take a look at this functioning code snippet: var randNum = x => () => Math.floor(x*Math.random()); var random10 = randNum(10) times(random10, 10) // => [6, 3, 7, 0, 9, 1, 7, 2, 6, 0] The function randNum creates a random number generator that wi ...

Tips for creating immersive 3D games on the web

I am fairly new to the world of HTML and Javascript, but I am diving into the Udacity interactive 3D course and experimenting with three.js + WebGL. I have managed to create and somewhat understand this: So far. (I am struggling to comprehend the API ...