反应应用程序看不到 Heroku 环境变量

时间:2021-04-02 02:59:39

标签: node.js reactjs heroku environment-variables

我有一个主要基于 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

我设置的环境变量, enter image description here

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

{process.env.REACT_APP_LOCAL_TEST_ENVIRONMENT}