Setting up Axios with Npm

Is it possible to set the baseURL for axios using an npm parameter?

I am interested in being able to use a command like this

npm run build --baseUrl={url address}
and have the axios configuration automatically update the baseURL parameter with the value from the command.

Can this be achieved?

Answer №1

Using --baseUrl in such a manner may not be advisable, as it can lead to the need for repetitive definition of --baseUrl across various scripts like npm start, resulting in convoluted code.

A suggested approach to address this issue is as follows:

  • Create an .env file containing development environment variables. Ensure to add this file to your .gitignore and refrain from pushing it to the production server as it is intended for development use only.
  • Add a new variable named BASE_URL as shown below:
BASE_URL=http://YOUR_API_LOCATION/
  • Utilize libraries such as dotenv (installed via npm i dotenv) to facilitate reading of .env files.

  • Develop a new utility for axios, for instance:

// client.js
const axios = require('axios');
const dotenv = require('dotenv');

// Retrieve all environment variables here.
dotenv.config({ path: '.env' });

// Establish a new axios instance utilizing the base url retrieved from the '.env' file.
const axiosInstance = axios.create({
  baseURL: process.env.BASE_URL,
  /* other custom settings */
});

module.exports = axiosInstance;

You can make use of your axiosInstance as demonstrated below:

// request.js
const axiosCustomClient = require('./client');

axiosCustomClient.get('relative/path/to/your/api');

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

Running sonar scans on a software development project that includes both C# and JavaScript code

I've been having trouble setting up code analysis with Sonar for a C# project, specifically because I also want to analyze JavaScript in the web project. Unfortunately, it seems that running multi-module projects on a .NET solution is not possible acc ...

Issues with the Web Share API navigator.share feature arise when users choose to cancel the share dialog on both IOS

Encountering a surprise error when utilizing MOBILE SHARE (navigator.share) that appears after cancelling the share flow. Although users can acknowledge the message and proceed, this unexpected error response occurs. STEPS TO REPLICATE 1. Tap the SHARE i ...

Checking for different elements between two arrays in AngularJS can be achieved by iterating through

I am working with two arrays: $scope.blinkingBoxes=[1,3,2] In addition, I have another array named $scope.clickedBoxes where I push several values. Currently, I use the following code to determine if the arrays are identical: if(angular.equals($scope.bli ...

eliminate a mesh from the view following a mouse hover event triggered by a raycaster

            When loading a gltf model, I want to make sure that a mesh is only displayed when the object is hovered over. I have successfully managed to change its material color using INTERSECTED.material.color.setHex(radioHoverColor); and reset it ...

Sending an array from node.js/express to a jade template

Feeling a bit lost with my code here.. questions.js questions = []; questions.AA = 'First' questions.BB = 'Second' questions.CC = 'Third' res.render('questions', { title: questions[CC], questions: questio ...

Import information onto the `ready` function within a Dashing Widget's Coffeescript

How can you ensure that data is polled upon startup of a dashing widget? ready gets triggered once the widget finishes rendering. class Dashing.Tagcloud extends Dashing.Widget ready: -> onData: (data) -> The widget I've created utilizes ...

Extract data from a JSON object using targeted translations

When responding to my client, I have data in a JavaScript format. The table I am loading requires specific field names. Is there a way to map a key in the JSON to a field name in the JSON object? This is my current approach: this.resArray = Array; this.r ...

Tips for Managing Errors During Zip File Extraction in Node.js

Currently, my task involves uploading a zip file, extracting it on the server side, and handling any errors that may occur during the extraction process. I am attempting to achieve this using the following code: var zip = new AdmZip(x); zip.extractAllTo( ...

The combination of setInterval() and if(confirm()) is not possible in pure JavaScript

One day, I encountered a simple if(confirm()) condition like this: if(confirm('Some question')) { agreed_function(); } else { cancel_function(); } function agreed_function() { console.log('OK'); } function cancel_function( ...

What could be the reason for Firebase still throwing errors after executing NPM install command?

After successfully running NPM Install without any issues, I encounter an error when attempting to deploy Firebase. Here is a snippet of the NPM install process: xxxxxx-MacBook-Pro:Edzuki-Learning xxxx$ npm install audited 375 packages in 3.733s found 0 ...

"Implement a feature to recognize and handle various file extensions within an npm

I need help with my npm script where I am trying to include both ts and tsx file extensions. My current code snippet is as follows: "test": "mocha ..... app/test/**/*.spec.{ts,tsx}" Unfortunately, the above syntax is not working correctly. Can someone pl ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Initiating change upon componentDidMount

Seeking advice on implementing a transition with react and css. The goal is to apply a class to the span element to achieve the desired animation effect – see illustration below. Curious to know whether the issue lies in the css implementation or the ja ...

struggling to locate path in Node.js REST API using Express and ES6 classes

I'm currently setting up a RESTful API using Node.js, and I've opted to utilize ES6 classes for the task. This is how my app.js file appears: const express = require("express"); const morgan = require("morgan"); const bodyParser = require("body- ...

API Post request encountering fetch failure

The route "/api/users/register" on my express server allows me to register an account successfully when passing data through Postman. However, when trying to register an account using the front-end React app, I'm encountering a "TYPE ERROR: Failed to ...

What are the steps for posting and setting up a custom npm package on GitHub packages under an organizational account?

In our monorepo, we have a shared package named "@myorganization/common" that is utilized by both the application and Google cloud functions. For Google cloud functions to use the package, it must be published to a repository. However, we do not publish c ...

What strategies can be employed to enhance the natural movement of dots on my HTML canvas?

Check out my code pen here I'm looking for feedback on how to make the movement of the canvas dots more fluid and liquid-like. I've experimented with restricting the direction for a certain number of renders (draw()), which has shown some impro ...

Retrieve the latest inserted ID in a Node.js application and use it as a parameter in a subsequent query

I am currently working with an SQL database that consists of two tables, namely club and players. These tables are connected through a one-to-many relationship. Although the query in my node.js code is functioning properly, I am facing an issue retrieving ...

Counting and finding results in MongoDB

Seeking assistance! I am in need of making a regular query to my database, but due to the large size of my collection (10000 documents), I must include $limit and $skip. While I have sorted out that part, I now aim to get a count of all the documents, even ...

Can React Context be maintained while navigating between pages cached with Next.js Router Cache?

In my current setup using Next.js 14 with the app router, I have implemented two routes: /businesses and /people. Each route contains a top-level React Server Component called Page, which fetches the respective list data for that page. The Page component t ...