ReactJs 如何传递自定义服务器主机名?

ReactJs How to pass custom server hostname?

当我需要获取数据时,运行 我的 React 应用程序要在 url 中使用时,我希望能够传递自定义服务器主机名。服务器目前在我的本地计算机上 运行,所以当我获取(url)时,我一直在使用“http://localhost:...." which has worked perfectly. But I want to be able to have to pass a custom host name, such as my ip address, to be used in the url (i.e. http://ipaddress:....

我试过这样启动我的应用程序:

serverhost=ipaddress npm start

然后在我的 package.json 文件中

"scripts" : {
   "start": "react-scripts start $serverhost"
}

在 start.js 中我可以访问 process.env.serverhost,但我希望能够在浏览器中访问主机名以进行实际的提取调用。我不想在 package.json 中的 "config" 或 .env 文件中设置主机名,因为它必须能够更改(我的印象是这是不可能的)。我只想能够访问在我的 src 文件的命令行中作为参数给出的服务器主机名。

(我在某处读到关于做

REACT_APP_MY_VAR=test npm start 

然后以

访问它
process.env.REACT_APP_MY_VAR

在 src 文件中,但是当我尝试获取时(url)我遇到了一堆解析失败 URL 错误)

编辑:我尝试使用 REACT_APP 变量并且在获取

时不再出现解析 URL 错误

您可以在您的 index.html 中设置一个 base 标签,为您以后的所有请求设置基础。

您可以通过读取 document.location 并映射您需要的路径来动态创建基本标签。

请注意,所有相对路径都将从您的 baseTag 映射

一个例子是这样的

<base href="https://www.dog.ceo/" />

然后像这样创建一个请求

fetch('api/breeds/list/all')
  .then( response => response.json() )
  .then( ({message}) => console.log( message ) );

那个电话的完整地址是https://www.dog.ceo/api/breeds/list/all

您可以为每个环境创建 .env 文件,然后设置

REACT_APP_API_ENDPOINT=http://localhost.whatever

例如 .env.development

REACT_APP_API_ENDPOINT=http://localhost.whatever

.env.production

REACT_APP_API_ENDPOINT=http://production.whatever

env 变量的用法在这里解释 https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#what-other-env-files-can-be-used

最后,您可以将它添加到您的脚本中,例如

"scripts" : {
   "start": "REACT_APP_API_ENDPOINT=http://localhost.whatever npm/yarn start"
   "start-production": "REACT_APP_API_ENDPOINT=http://production.whatever npm/yarn start"
}

如果你根本不想使用上述方法,那么将你的 ip 分配给某个变量并将其添加到 运行 你的应用程序

的命令中
"scripts" : {
   "start": "REACT_APP_API_ENDPOINT=$(curl ifconfig.me) npm/yarn start"
   "start-other: "REACT_APP_API_ENDPOINT=$(echo MY_VAR_WITH_IP) npm/yarn start"
}

然后从 process.env.REACT_APP_API_ENDPOINT

访问您的 url