首页 > 解决方案 > 在 .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"
  },

标签: reactjsreact-redux

解决方案


您可以在 .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,
  }),
});


推荐阅读