简体   繁体   中英

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 (eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM