V
V
Vadim2021-08-21 17:06:20
Software Deployment
Vadim, 2021-08-21 17:06:20

How do you change localhost to the server name in a React app?

There are such sections of code in the React application where localhost is registered, for example

export const getData = () => {
  return fetch("http://localhost:3000/data.json", {
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
  })
    .then((response) => response.json())
    .catch((error) => {
      throw error;
    });
};

When you do a yarn build, this localhost:3000 compiles and ends up in the ./build folder and, of course, does not work correctly on a server like mysupersite.ru.

How can I automate the build so that it is ready for production? At least to replace localhost with the desired server name? Is it really only scripts or are there methods of React itself or best practices?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Shitskov, 2021-08-21
@Viji

You can specify a relative path without hostname.
You can get the current server address from window.location
. You can substitute it at the application build stage through environment variables in webpack or react.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question