3👍
✅
I don’t think it is possible if you call that --baseUrl
like that, as if you do it like that, you’re going to have to define --baseUrl
for npm start
and other scripts, and you’ll quickly end up with a spaghetti code.
I humbly suggest a way to mitigate this issue:
- Create an
.env
file that is filled with your environment variables for development. Add this to.gitignore
and don’t push this into your production server. This file is not used for production. - Add a new
BASE_URL
variable, like:
BASE_URL=http://YOUR_API_LOCATION/
-
Use libraries like
dotenv
(install bynpm i dotenv
) so you can read.env
files. -
Create a new utility for axios, let’s say:
// client.js
const axios = require('axios');
const dotenv = require('dotenv');
// get all environment variables here.
dotenv.config({ path: '.env' });
// create a new axios instance with the base url from your '.env' file.
const axiosInstance = axios.create({
baseURL: process.env.BASE_URL,
/* other custom settings */
});
module.exports = axiosInstance;
You can reuse your axiosInstance
like this:
// request.js
const axiosCustomClient = require('./client');
axiosCustomClient.get('relative/path/to/your/api');
Source:stackexchange.com