reactjs - 在 .env 文件 React 应用程序中设置 PUBLIC-URL
问题描述
嗨,我是 React 应用程序的新手。我想在 .env 文件中设置 Public_URL。
.env 文件(我设置了我的 url 链接)
PUBLIC_URL="http://localhost:8000/api";
登录.tsx 文件
const response = await fetch("/login", {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
body: JSON.stringify({
userName,
password
})
});
当我启动应用程序时,我的应用程序应该可以正常工作。但是在我的登录页面中,我将登录按钮 My Url 调用提交到 http://localhost:3000/login。但我需要设置 http://localhost:8000/api 。我不知道如何设置它。请发送正确的示例。
包.json
"scripts": {
"start": "env-cmd -f .env react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
解决方案
您可以在 .env 文件中为您的端点设置另一个变量,例如:
REACT_APP_API_ENDPOINT=http://localhost:8000/api
PUBLIC_URL
已经用作 React 获取应用程序依赖项的基本 url。
在您的组件中,您可以通过以下方式获取环境变量:
const { REACT_APP_API_ENDPOINT } = process.env;
const response = await fetch(`${REACT_APP_API_ENDPOINT}/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({
userName,
password,
}),
});
推荐阅读
- node.js - 动态 GatsbyJS + Node Express 部署
- node.js - Nodejs议程作业调度程序-如何将在同一数据库扫描中运行的多个作业分组为1个批处理作业?
- webrtc - 了解 WebRTC 中的 SFU、TURN 服务器
- python - 类型提示 pandas DataFrame 切片行的索引
- jekyll - Jekyll:链接一个类别中的下一个/上一个排序的帖子
- angular - 按日期分组列表
- swift - 如有必要,使用 Finder 提示用户权限打开下载目录
- mysql - 在字符串中查找字符串模式
- python - 如何在 GCP 云函数中访问二进制文件 [PYTHON]
- yaml - 此处不允许映射值在“
"