How to set backEnd URL in frontEnd react

Viewed 7795

I'm a beginner on react (and front end in general).I just made a rest full API on Java, and i want to ask you guys, what is the proper what to tell the fetch() function on react's .jsx the backend URL, I currently have it burned on a constant, but i suppose that a more elegant way of doing this must exist.

thanks for your help, and happy coding.

EDIT: To clarify what i mean this is some example code that i have:

In the back end i have a restfull service like this:

@CrossOrigin(origins = "http://localhost:3000")
@RequestMapping("/recursosTotales")
public List<Recurso> recursosTotales(){

    ConectorBd conectorBd =new ConectorBd();
    conectorBd.start();
    return  conectorBd.recursoList();
}

In the front i have a fetch that calls that restfull service like this:

fetch("http://localhost:8090/recursosTotales")
  .then(response => response.json())
  .then(response => {
    this.setState({ products: response });
  });

As you guys can see, the URL of the backend is burned, what i want to know is how i make some kind of global variable, that in case i have to change the Server URL in only change it in one place.

I tried using dotenv library, but for what i read the process.env does not work on the .jsx files because they are part of the client side of the app, and env only works on the server side. I cannot fully understand that principle.

Anyway i hope that i make my question more clear. And thanks to all the people who have already answer.

EDIT 2

OK, people, i finally learned how to properly use dotenv, and it solve my requirement, thanks to all for your help and time.

4 Answers

If your frontEnd and backEnd are equal hostname, use window.location.hostname.

This is stackoverflow's window.location

enter image description here

Personally, I'd want it to be a configurable value so that I can easily change it after it's bundled and deployed. Unless the URL is a domain name that you can change where it gets redirected to via some other configuration (i.e. apache), if you ever change the address of the backend server, you'll have to make changes in the code which can be more time consuming than changing a configuration.

This is assuming that you trust everyone who might have access to this configuration file.

You can convert API raml spec to Json format to list API formatted. Then you read this Json and map to fetch method. I think it's a reflection way.

Related