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');