gpt4 book ai didi

reactjs - 在 .env 文件 React 应用程序中设置 PUBLIC-URL

转载 作者:行者123 更新时间:2023-12-02 02:11:17 28 4
gpt4 key购买 nike

Hi I am new in react application. I want to set Public_URL in .env file .

.env 文件(我设置了我的url链接)

PUBLIC_URL="http://localhost:8000/api";

Login.tsx file

const response = await fetch("/login", {
method: 'POST',
headers: {'Content-Type': 'application/json'},
credentials: 'include',
body: JSON.stringify({
userName,
password
})

});

When i start the application, My application should be work fine. But In my Login page I submit the Login button My Url call to http://localhost:3000/login. But I need to set http://localhost:8000/api . I don't know how to set it. Please send the correct example.

包.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,
}),
});

关于reactjs - 在 .env 文件 React 应用程序中设置 PUBLIC-URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67709638/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com