angularjs - 无法从 Grunt 服务器运行的 Node + AngularJS 应用程序中读取环境变量

标签 angularjs node.js ubuntu gruntjs environment-variables

我已经在 AngularJS 和 Firebase 上创建了一个应用程序。我决定将 Firebase 凭据存储为环境变量。我在 Ubuntu 上,我使用 Grunt 运行开发服务器。

我尝试创建一个 .bashrc 文件来存储如下所示的环境变量(值插入在引号之间)。

export APIKEY=""
export AUTH_DOMAIN=""
export DATABASE_URL=""
export STORAGE_BUCKET=""
export MESSAGING_SENDER_ID=""

然后我有一个使用这些变量配置 Firebase 的 config.js 文件。

var config = {
    apiKey: process.env.APIKEY,
    authDomain: process.env.AUTH_DOMAIN,
    databaseURL: process.env.DATABASE_URL,
    storageBucket: process.env.STORAGE_BUCKET,
    messagingSenderId: process.env.MESSAGING_SENDER_ID
};

firebase.initializeApp(config);

但是,我认为 Grunt 不会获取这些值,因为无论我运行 Grunt 服务器还是使用 node server.js 运行应用程序,它都不会为这些变量找到值。我还尝试先从命令行创建变量,就像这样(在引号之间插入值)。

$ export APIKEY=""

无论如何,我的应用无法看到环境变量。它在控制台中传递此错误。

Uncaught ReferenceError: process is not defined at config.js:2

当我将值直接插入 config.js 文件时,应用程序运行良好。我尝试了多种在 Ubuntu 中配置变量的选项,但似乎都没有用。

编辑: 可能还值得注意的是,Heroku 也无法识别这些变量,尽管我已经在 Heroku 中注册了它们,但它会出现相同的错误(process is not defined)。会不会是 Angular 的东西?

最佳答案

您需要在 config.js 文件中创建一个包含您的凭据和要求的文件 env.js。您可以忽略 Git 中的文件。

env.js

module.exports = {
  APIKEY: "your-api-key",
  AUTH_DOMAIN: "your-auth-domain",
  DATABASE_URL: "your-database-URL",
  STORAGE_BUCKET: "your-storage-bucket",
  MESSAGING_SENDER_ID: "your-messaging-sender-id"
}

.gitignore

env.js

config.js

var keys = require('env');

var config = {
  apiKey: keys.APIKEY,
  authDomain: keys.AUTH_DOMAIN,
  databaseURL: keys.DATABASE_URL,
  storageBucket: keys.STORAGE_BUCKET,
  messagingSenderId: keys.MESSAGING_SENDER_ID
};

firebase.initializeApp(config);

关于angularjs - 无法从 Grunt 服务器运行的 Node + AngularJS 应用程序中读取环境变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466280/

相关文章:

angularjs - $cookies 与 angularjs 1.4 到期日期

AngularJS app.run() 文档?

javascript - 以 Angular 解决 promise

javascript - 通过node.js和socket.io向特定用户发送数据

javascript - 如何在 Node.js 后端和前端的单独 js 文件中使用函数?

ubuntu - 如何解决 apt-get 中的分布冲突

javascript - 将对象注入(inject)到服务函数中

node.js - nodejs 简单的 TCP 聊天,服务器没有收到客户端消息

linux - 无法进行 LibreOffice 在线构建

linux - 为什么我不能在 Ubuntu 中使用 wget 获取此页面?