是否可以在客户端的前端使用React服务器环境变量? [英] Is it possible to use a React server enviroment variables into frontend at client side?

查看:94
本文介绍了是否可以在客户端的前端使用React服务器环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 PKG 为我的Appolo GraphQL服务器制作可执行.exe文件+ React客户端将所有内容捆绑到一个exe文件中.它正在工作,现在有一个要求:应用程序应该从某个地方读取IP地址,并将其用作主机,端口等的常量.

在服务器端,我正在使用 fs.readFileSync -可以.我可以读取任何文本文件,因为它是nodejs服务器端.现在,要求是将该IP传递给客户端文件->进入静态文件夹(标记为*),在其中我有用客户端IP连接的constant.js(内部编译为static/js ..).服务器端文件(NodeJs + React):

 ├───build│└───静态│├───css│├───* js *│└───媒体├───config├───src│├───芯│├───graphql│├───guardServer│└───pg└───SSL 

客户端React文件树:

 <代码>├───.idea├───.vs│└───反应│└────v16├───建│└───静态│├───css│├───js│└───媒体├───公众└───src├───组件│├───芯││├───功能││└───模态│└───模块│├───账户│├───adminPanel││└───页面│├───存档│├───小时部门││└───页面│├───原木│├───显示器│└───报告├───config└───图像 

所以我的行动是: npm run build 一个聪明的人.然后,我拿文件夹 build 替换服务器端文件:server/build文件夹.然后,我在服务器端进行操作- npm run build 并接收一个exe文件.该exe的服务器部分(/server/index.js)可以读取settings.txt,但不能读取/server/build/static/js内的该部分(客户端)...

我的问题是:是否可以通过某种方式修改webpacker,并且服务器环境变量将可以通过 process.env.myvar 命令从客户端访问(并且将是动态的)?

如果没有,在这种情况下是否可以使用任何技巧?请注意,由于文件系统快照限制,现在允许使用PKG的 fs.writeFileSync .

服务器端代码:

  let fileContent = fs.readFileSync("D:\\ settings.txt","utf8");让getIp = JSON.parse(fileContent);//工作正常,获得IP 

使用Apollo客户端的客户端,而对于他来说,我确实需要从服务器端传递该IP,请问有什么想法吗?

Ajeet Shah的更新.我做了什么:

 在我的server.js上-var __SERVER_DATA__ ="192.168.0.111";在客户端的index.html中-< script>window.SERVER_DATA = __SERVER_DATA__;</script>在客户端的index.js中-console.log(window.SERVER_DATA); 

更新:

我想我将在微型HTTP服务器上停留一段时间,该HTTP服务器将在localhost:port上运行.从那里我可以自由读取任何设置.谢谢大家提供有用的答案.

我选择了带有更多选项的答案,并且有关于localStorage的建议.非常感谢大家的注意.仍在尝试实现所提供的方法.

更新.

我已经完成了这一步.我已经使用了html变量 window.SERVER_DATA = __SERVER_DATA __ ,如此处所述-解决方案

在后端技术中,所有问题都由环境变量解决,当您必须将应用程序移动到各个阶段(开发,暂存,生产)时,这是一个好习惯./p>

在客户端技术(react,vue,angular或simple js)中,动态获取这些值非常复杂.

检查此答案以了解变量如何在js客户端中工作或如何注入动态值

https://stackoverflow.com/a/54271114/3957754

REACT_APP

一种策略是使用REACT_APP变量

https://create-react-app.dev/docs/adding-custom-environment-variables/

因此,如果您在服务器端创建此变量

 导出REACT_APP_remote_ip 

React库将为您创建一个变量.您可以在任何react文件中使用thia var

  process.env.remote_ip 

Webpack

类似于REACT_APP webpack,它提供了一个选项,可以将服务器端变量公开为可在任何.js文件中使用的全局javascript变量

 新的webpack.DefinePlugin({API_BASE_URL:JSON.stringify(process.env.API_BASE_URL)}) 

/设置

另一个选择是在nodejs服务器端创建一个端点.该端点可以访问环境值,因此您可以返回所需的任何内容:

  res.json({"ip1":process.env.remote_ip_1}); 

此后,您只需要在react或javascript文件的最早期js或入口点中调用或调用此端点/settings.

最后,/settings的返回可能显示为全局javascript值或存储在浏览器的本地存储区中

I am using PKG, to make a executable .exe file for my Appolo GraphQL Server + React client bundled all into one exe file. It's working, and now there is requirement: app should read from somewhere an IP address and use it as constants for host, port, etc.

From server side I am using fs.readFileSync - which is okay. I can read any text file as it's nodejs server side. And now the requirement is to pass that IP to the client files -> into the static folder (marked *), where I have constant.js with IP of client to connect inside (compiled static/js..). Server side files (NodeJs+React):

├───build
│   └───static
│       ├───css
│       ├───*js*
│       └───media
├───config
├───src
│   ├───core
│   ├───graphql
│   ├───guardServer
│   └───pg
└───SSL

Client React files tree:

├───.idea
├───.vs
│   └───React
│       └───v16
├───build
│   └───static
│       ├───css
│       ├───js
│       └───media
├───public
└───src
    ├───components
    │   ├───core
    │   │   ├───functions
    │   │   └───modal
    │   └───modules
    │       ├───account
    │       ├───adminPanel
    │       │   └───pages
    │       ├───archive
    │       ├───hr-department
    │       │   └───pages
    │       ├───logs
    │       ├───monitor
    │       └───reports
    ├───config
    └───images

So my actions are: npm run build a clent. Then I taking the folder build and replacing a server side files: server/build folder. Then I'm doing on the server side - npm run build and receiving an exe file. WHERE a server part (/server/index.js) of this exe can read a settings.txt, but not that part (client) which is inside /server/build/static/js...

My question is: is it possible by modifying webpacker somehow, and server environment variable will be accessible (and will be dynamic) from client side with command process.env.myvar?

If not, if there are any tricks I can utilize in this case? Please note that PKG's fs.writeFileSync is now allowed due to the filesystem shapshot restriction.

Code of server side:

let fileContent = fs.readFileSync("D:\\settings.txt", "utf8");
let getIp=JSON.parse(fileContent); //fine working, got IP

Client using Apollo Client and exactly for him I need to pass that IP from server side, any ideas please?

Update for Ajeet Shah. What I did:

On my server.js - var __SERVER_DATA__ = "192.168.0.111";

in index.html of client - <script>
      window.SERVER_DATA = __SERVER_DATA__;
    </script>

in index.js of client - console.log(window.SERVER_DATA);

Update:

I think I will end up for a while with the tiny http server, which will run on localhost:port. And from there I can freely read any settings. Thank you All for usefull answers.

I've chosen the answer with more options and there was advise about localStorage. Thank you all much for heads up. Still trying to implement offered methods.

Update.

I've finishied doing this. I've used an html variable window.SERVER_DATA = __SERVER_DATA__ as described here - https://create-react-app.dev/docs/title-and-meta-tags/#injecting-data-from-the-server-into-the-page. I will decide later on what to do with best answer, if nobody will post extra ones.

解决方案

In backend technologies, everything is solved with environment variables which is a good practice when you have to move your app through stages( dev, staging, prod).

In client side technologies( react, vue, angular or simple js) the obtainment of these values dynamically is complicated.

Check this answer to understand how variables work in js client side or how to inject dynamic values

https://stackoverflow.com/a/54271114/3957754

REACT_APP

One strategy is use the REACT_APP variables

https://create-react-app.dev/docs/adding-custom-environment-variables/

So if you create this variable in your server side

export REACT_APP_remote_ip

React library will create a variable for you. You can use thia var in any react file

process.env.remote_ip

Webpack

Similar to REACT_APP webpack offer an option to expose server side variables as global javascript variables ready to use in any .js file

new webpack.DefinePlugin({
  API_BASE_URL: JSON.stringify(process.env.API_BASE_URL)
})

/settings

Another option is to create an endpoint in your nodejs server side. This endpoint has access to the environment values, so you can return anything you want:

res.json({
  "ip1": process.env.remote_ip_1
});

After this, you just need to call or invoke this endpoint /settings in the most early js or entrypoint of your react or javascript files.

Finally, the return of /settings could be exposed as global javascript values or stored in localstore of browser

这篇关于是否可以在客户端的前端使用React服务器环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆