如果可能会更改,则最惯用的方法来存储API的端点?
我正在构建一个React应用程序,作为其中的一部分,我有一台在本地端口上运行的后端Express服务器,但这是由于部署的变化而导致的,可能会在将来更多。将该API地址存储在前端的最佳方法是什么?
目前我使用:
localstorage.setItem(“ apiendpoint”,“ http://10.1.1.1.177:8080”);
,但这感觉很笨拙且不安全。
我不知道该方法的特定问题,因为这是在每个页面负载上设置的,这意味着它不能更改,但是要做的是错误的。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将环境变量与React使用。基本上,这将允许您使用.ENV文件,并且可以将端点命名为API_ENDPOINT = http://10.1.1.1.177:8080在开发环境中。在生产环境中,您可以使用其他URL,但具有相同的API_ENDPOINT名称。
您可以参考以下链接
You can use environment variables with React. Basically, this will allow you to use a .env file and you can name the endpoint as API_ENDPOINT=http://10.1.1.177:8080 for your development environment. On your production environment, you can use a different url but with the same API_ENDPOINT name.
You can reference the below link
https://create-react-app.dev/docs/adding-custom-environment-variables/