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

时间:2018-07-27 20:47:44

标签: reactjs parameter-passing fetch command-line-arguments

我希望能够在运行我的react应用程序时传递自定义服务器主机名,以便在需要获取数据时在url中使用。该服务器当前正在我的本地计算机上运行,​​因此当我提取(url)时,我一直在使用“ http://localhost:....”,该服务器运行良好。但是我希望能够传递一个自定义的主机名,例如我的IP地址,以便在url中使用(即http://ipaddress:..。)。

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

serverhost=ipaddress npm start

然后在我的package.json文件中

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

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

(我读过有关做某事的

REACT_APP_MY_VAR=test npm start 

,然后以

访问
process.env.REACT_APP_MY_VAR

在src文件中,但是当我尝试获取(url)时,我遇到了很多解析URL错误的操作)

编辑:我尝试使用REACT_APP变量,并且提取时不再解析URL错误

2 个答案:

答案 0 :(得分:0)

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

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

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

一个例子就是这样

 function send_email() {
  // send mail
}
add_action( 'event','send_email' );

// put this line inside a function, 
// presumably in response to something the user does
// otherwise it will schedule a new event on every page visit

 wp_schedule_single_event( time() + 180, 'event' );

然后创建这样的请求

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

该呼叫的完整地址为fetch('api/breeds/list/all') .then( response => response.json() ) .then( ({message}) => console.log( message ) );

答案 1 :(得分:0)

您可以根据环境使用.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

这里https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#what-other-env-files-can-be-used

解释了env变量的用法

最终,您可以将其添加到脚本中,例如

"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

访问您的网址