【问题标题】:Heroku environment variables are not visible for the react appHeroku 环境变量对 React 应用程序不可见
【发布时间】:2021-06-29 00:09:19
【问题描述】:

我有一个主要基于 React 的前端应用程序,并且我创建了一个节点服务器来为该应用程序提供服务。构建并且一切都成功,并且 index.html 也被提供,但它不会读取我通过 heroku 应用程序设置(甚至来自 CLI)设置的环境变量。

Package.json 脚本

    "scripts": {
    "start": "node server",
    "start-dev": "react-scripts start",
    "start-windows": "set PORT=3001 && react-scripts start",
    "build": "react-scripts build",
    "postinstall": "npm run build",
    "test": "jest src/**/*.test.js",
    "eject": "react-scripts eject"
  }

节点服务器,

const express = require ('express')
const app = express();
const http = require('http').Server(app);
const path = require( 'path')
let port = process.env.PORT || 3000;

app.use(express.static(path.join(__dirname, 'build')));


app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'build') + '/index.html');
});

app.listen(port, () => {
  console.log(`App running on port ${port}`);
});

我在 js 中打印以下内容,

console.log('LOCAL_TEST_ENVIRONMENT --- ', process.env.LOCAL_TEST_ENVIRONMENT) // LOCAL_TEST_ENVIRONMENT ---  undefined
console.log('BACKEND_URL --- ', process.env.BACKEND_URL) // BACKEND_URL --- undefined
console.log('NODE_ENV --- ', process.env.NODE_ENV) // NODE_ENV --- production

我设置的环境变量,

我该如何解决这个问题?

【问题讨论】:

    标签: node.js reactjs heroku environment-variables


    【解决方案1】:

    访问环境变量时需要前缀REACT_APP_,试试

    {process.env.REACT_APP_LOCAL_TEST_ENVIRONMENT}
    

    【讨论】:

      猜你喜欢
      • 2020-07-31
      • 1970-01-01
      • 2021-05-03
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2020-07-02
      • 1970-01-01
      • 2021-12-28
      相关资源
      最近更新 更多