javascriptnetwork-programmingipipv4ifconfig

How to get ipv4 address of host in JavaScript/React


I currently have a react app and flask server running locally. The react app makes http requests to the flask server via axios (whenever a button is pressed for example). This is running on a raspberry pi.

I have been able to connect to the react app from other devices on the same network using my ipv4 address (e.g. http://10.32.24.152:3000). However, whenever I press a button, the react app will try to communicate with the flask server on localhost (which is the localhost of my other device, not the device that the react app is running on).

I think I would need to set the axios url to 10.32.24.152:5000 to make this work. I was wondering how to obtain the ipv4 IP address of the host dynamically in Javascript since I don't want to hardcode 10.32.24.152.


Solution

  • I figured it out. You can use window.location.host. This will be localhost if you access the website on the host directly, or it will be the host IP if you access the website from a different device.