I have written a React application (React+Vite) which makes some fetch requests.
Here is an example:
const fetchRows = async () => {
let rows = [];
const response = await axios.post(
'http://localhost:81/api/get_rows',
{}
);
rows.push(response.data['rows']);
return rows;
};
It doesn't matter too much what this code does. The important part is the hostname used in the request, in this case the POST request is directed to localhost:81
.
This works fine during development where the same machine is used to host the backend webserver, the NodeJS/React/Vite development environment/server and the web browser use to test the whole system.
Unsurprisingly, this no longer works in production, when my application and backend logic is deployed to a server on the cloud, and I am trying to interact with it from some other machine.
I do not have a domain name setup for this system. I can create one if absolutly necessary, however I would prefer to just hardcode the ip address in place of localhost rather than go and buy a domain name.
- I know that domain names are not expensive, I just don't want to configure it as this is for a demonstration project and it doesn't have any particularly important application other than as a demo.
Is there a relatively easy way to write some React code which uses an ip address in place of localhost
without resorting to hardcoding the address which obviously isn't a great solution?
eg: Is there a React or JavaScript function which can ask the host machine what its ip address is?
This might not be so easy since any machine has multiple ip addresses. (127.0.0.1
being an obvious example that all Linux hosts have.)
Any suggestions welcome. If buying a domain is easier, I'll just do that.
/api/get_rows
without host. nginx would serve everything except/api/*
from static files and for/api/*
it would act as reverse proxy for the backend on the other port.axios.get('/questions')
on this page it would end up fetching fromhttps://stackoverflow.com/questions
). And that's fine if that page is served by nginx and nginx also proxies/api/*
requests to the backend./api/*
routes to your backend. So you wouldn't call your backend directly, it would be routed through nginx to your backend. From the outside it would then all be under the same domain/IP and port (served by nginx).location /api {
proxy_pass http://your-server.com:81;
}
with your IP instead ofyour-server.com
(googlenginx api proxy
for more examples)