如果可能会更改,则最惯用的方法来存储API的端点?

发布于 2025-02-08 19:45:45 字数 269 浏览 2 评论 0 原文

我正在构建一个React应用程序,作为其中的一部分,我有一台在本地端口上运行的后端Express服务器,但这是由于部署的变化而导致的,可能会在将来更多。将该API地址存储在前端的最佳方法是什么?

目前我使用: localstorage.setItem(“ apiendpoint”,“ http://10.1.1.1.177:8080”); ,但这感觉很笨拙且不安全。

我不知道该方法的特定问题,因为这是在每个页面负载上设置的,这意味着它不能更改,但是要做的是错误的。

I am building a React app and as part of it, I have a backend Express server which runs on a local port, however this is due to change on deployment, and maybe more times in the future. What would be the best way to store the address of this API in the frontend?

Currently I use:
localStorage.setItem("apiEndpoint", "http://10.1.1.177:8080"); but that feels quite hacky and insecure.

I don't know the specific problem with that approach as this is set on every page load, meaning it can't be changed, but it feels wrong to do.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

池予 2025-02-15 19:45:45

您可以将环境变量与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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文