如何在JavaScript/React中获取主机的IPv4地址
我目前有一个React App和Blask Server在本地运行。 React App通过Axios向Blask Server提出HTTP请求(例如,每当按下按钮时)。这是在覆盆子Pi上运行的。
我已经能够使用我的IPv4地址从同一网络上的其他设备连接到React App(例如.24.152:3000 )。但是,每当我按下按钮时,React应用程序都会尝试与Localhost上的Blask Server通信(这是我的其他设备的本地主机,而不是React App正在运行的设备)。
我认为我需要将Axios URL设置为10.32.24.152:5000才能完成此工作。我想知道如何在JavaScript中动态地获取主机的IPv4 IP地址,因为我不想进行硬码10.32.24.152。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我发现了。您可以使用window.location.host。如果您直接访问主机上的网站,则将是本地主机,如果您从其他设备访问网站,则将是主机IP。
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.