Home > front end >  Dynamic Server Name for API Calls in React
Dynamic Server Name for API Calls in React

Time:06-23

I want to know when I start the front-end application using npm start by default it will run on localhost:3000 and will also start the backend server in python and it will start on localhost:5000. Then how I can know the server name or origin of the backend?

Here, I am hardcoding the server name here, now I want to make it dynamic.

Please give some suggestions. It will be beneficial for me.

if (production === false) {
    baseURL = "http://localhost:5000/getAll";
  }
  else {
    baseURL = "http://0.0.0.0:8080/getAll";
  }
  let statusInfo = [];
 
let job_input = {
    "username": "",
    "password": ""  
}
 
  useEffect(() => {
    const fetchData = async () => {
      await axios.post(baseURL, job_input) 
        .then((response) => {
          setJobData(response.data.job_details); //storing the data in jobData array
        })
        //Handling the exception
        .catch(error => {
          alert(error.Message);
        })
    }
    fetchData();
  }, [])

CodePudding user response:

You can do it by using the .env file.

if (process.env.NODE_ENV !== 'production')

Refer to the document below https://create-react-app.dev/docs/adding-custom-environment-variables/

CodePudding user response:

@Vivek Jhooria is right.

Prepare .env file in the base directory of the Project.

DOMAIN_URL=http://testapi.herokuapp.com
DOMAIN_URL_PROD=https://stage.herokuapp.com

Note: these url are fake.

And prepare start commands by 2 ways in package.json.

{
    "name": "testapp",
    "version": "0.1.0",
    ...
    "scripts": {
        "start": "react-scripts start",
        "start:dev": "set NODE_ENV=development && react-scripts start",
        ...
    }
}

And then, you can archieve your goal like this: Eg.

    let baseURL = null;
  if ((process.env.NODE_ENV === 'development') {
    baseURL = process.env.DOMAIN_URL;
  }
  else {
    baseURL = process.env.DOMAIN_URL_PROD;
  }
  let statusInfo = [];
 
let job_input = {
    "username": "",
    "password": ""  
}
 
  useEffect(() => {
    const fetchData = async () => {
           await axios.post(baseURL, job_input)
               .then(response=>{
               })
               .catch(error=>{});
    }
    
    fetchData();
  }, [])

Then you can run in two cases: development mode and product mode.

$ npm run start or

$ npm run start:dev

  • Related