简体   繁体   English

如何在快速后端server.js文件中设置一些值并在create-react-app代码中使用它?

[英]How to set some value in express backend server.js file and use it in create-react-app code?

I have a simple create-react-app with a express backend with only 1 file (server.js) whose job is to just execute build folder and start the web app. 我有一个简单的create-react-app,带有一个仅包含1个文件(server.js)的快速后端,其工作是只执行构建文件夹并启动Web应用程序。

server.js code looks like below: server.js代码如下所示:

const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express()
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})


// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})

Below is how my react app starts? 以下是我的应用程序如何启动?

"scripts": {
    "postinstall": "npm run build",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start": "NODE_ENV=prod node server.js",
    "develop": "react-scripts start"
  },

What I'm trying to achieve now? 我现在想要实现什么?

1.) My create-react-app is having some components like drop-downs, radio-buttons etc and based upon some selections fetch rest-api calls are done in react code app.js etc and accordingly data came in the response is loaded on the page. 1.)我的create-react-app具有一些组件,例如下拉菜单,单选按钮等,并根据一些选择在反应代码app.js等中获取rest-api调用,并相应地加载响应中的数据在页面上。

2.) Now, there are two rest-api end-points. 2.)现在,有两个rest-api端点。 One is dev and one is prod. 一个是开发人员,一个是产品。 For eg: www.example-dev.com/ , www.example-prod.com/ . 例如: www.example-dev.com/ , www.example-prod.com/

3.) So, based upon what cloud environment is determined in server.js code using process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' 3.)那么,根据使用process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'在server.js代码中确定的云环境process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' on which my create-react-app is running, i want to call respective rest-api end point like www.example-{env}.com/ process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod' ,正在运行我的create-react-app,我要调用各自的rest-api端点,例如www.example-{env}.com/

4.) So, i want to know the right way to set this value in server.js and use it in the react-app some component class wherever i want. 4.)因此,我想知道正确的方法来在server.js设置此值,并在我想要的任何组件类的react-app中使用它。

For eg: 例如:

Below is some react component piece of code, where i want to use env value set in server.js: 以下是一些React组件代码,我想使用server.js中设置的env值:

 handleOnChange = async selectedObj => {

      let responseObj = await callRestAPI(`www.example-${env}.com`);
      this.props.onChange(selectedObj);
  };

Please help. 请帮忙。

There are multiple ways to do this, here are few different ways 有多种方法可以执行此操作,以下是几种不同的方法

  1. Using create react app docs REACT_APP thing 使用create react app docs REACT_APP的东西
  2. Use a templating engine for index.html 对index.html使用模板引擎
  3. have endpoint as /config 将端点作为/ config
  4. create a js file dynamically, include it in your index.html 动态创建一个js文件,并将其包含在index.html中

1 to 3 ways you can find doc online 您可以通过1到3种方式在线查找文档

for 4th way here is how you can do 对于第四种方式,这是你怎么做

fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : ${process.env.ENVIRONMENT_NAME}}`);

Make sure you do this before express.static 确保在express.static之前执行此操作

With your code above, here is how it looks 上面的代码是这样的

const path = require('path')
const express = require('express')
const isProduction = process.env.NODE_ENV === 'prod'
const port = process.env.PORT ? process.env.PORT : 3000
const app = express();
const fs = require('fs');
var env = ""

// check below environment variable to identify on what environment on cloud service web-application is running
process.env.ENVIRONMENT_NAME === 'dev' ? env = 'dev' : env = 'prod'

// Add expressjs 'logger' plugin for printing logs and FE errors
app.use(
    logger({
        noop: isProduction
    })
)

app.use((req, res, next) => {
    // if i try to log env name like below i'm able to see the value
    // but if i try to log this anywhere like below in react code (it's always undefined)
    console.log(process.env.ENVIRONMENT_NAME);
})



fs.writeFileSync(path.join(__dirname, './build', 'config.js'), `window.SERVER_DATA = { env : "${process.env.ENVIRONMENT_NAME}"}`);

// Serves static assets
app.use(express.static('./build'))
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, './build', 'index.html'))
})

app.listen(port, (error, result) => {
    if (!isProduction && error) {
        console.log(error)
    }
    console.log('Server running on port ' + port)
})

update your index.html to use our new js file 更新您的index.html以使用我们的新js文件

<script src="./config.js"></script>

in your react component, you can access by 在您的react组件中,您可以通过

console.log(window.SERVER_DATA)

working example: 工作示例:

https://codesandbox.io/embed/express-5o8ei https://codesandbox.io/embed/express-5o8ei

You can provide an environment variable that starts with REACT_APP_ for example REACT_APP_ENVIRONMENT_NAME 您可以提供以REACT_APP_开头的环境变量,例如REACT_APP_ENVIRONMENT_NAME

And in your react code you can access it like this: 在您的反应代码中,您可以像这样访问它:

let env = process.env.REACT_APP_ENVIRONMENT_NAME;    
let responseObj = await callRestAPI(`www.example-${env}.com`);

You can also update the build script to pass the variable like this 您还可以更新构建脚本以像这样传递变量

"build": "REACT_APP_ENVIRONMENT_NAME=$ENVIRONMENT_NAME react-scripts build",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM