process.env变量即使在导出后也未定义 [英] process.env variables are undefined even after export

查看:548
本文介绍了process.env变量即使在导出后也未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Node.js Express应用程序,并希望使用环境变量来设置服务器应在其上运行的端口.

I'm writing a Node.js express app and want to use environment variables for setting the port on which the server should run.

但是,我似乎无法获得process.env.PORT来读取我的PORT环境变量.

However, I can't seem to get process.env.PORT to read my PORT environment variable.

我已经使用export定义了PORT环境变量,如下所示: export PORT=1234我还​​将此行添加到了~/.bash_profile文件中,但process.env.PORT仍未定义.

I've defined the PORT environment variable using export like so: export PORT=1234 I've also added this line to the ~/.bash_profile file, but process.env.PORT remains undefined.

当我在终端中运行echo $PORT时,它会正确显示值(1234).

When I run echo $PORT in terminal, it displays the value (1234) correctly.

我正在运行Node V0.12.7和OSX El Capitan 10.11.1,实际上找不到任何其他线索可能导致这种情况.

I'm running Node V0.12.7 and OSX El Capitan 10.11.1 and really can't find any extra clues on what might be causing this.

谢谢!

这是在尝试将process.env.port分配给port变量

Here's the code executed before trying to assign process.env.port to the port variable

var app = require('../app');
var proxy = require("../proxy");
var http = require('http');
var nconf = require('nconf');
nconf.file(__dirname + "/appConf.json");
var appSettings = require('../appSettings');

var port = normalizePort(process.env.PORT || 8080);

推荐答案

有一个很棒的npm软件包,名为dotenv,它将自动从与您的nodeJS应用程序位于同一目录中的名为.env的文件中加载任何环境变量. .这样可以为您提供不同的PORT变量项目,而不是在所有终端上全局定义一个PORT.

There's a great npm package called dotenv, that will auto-load any environment variables from a file called .env in the same directory as your nodeJS application. This could give you a differentPORT variable project to project, instead of globally defining one PORT across all terminals.

就其他所有内容而言,听起来好像PORT应该在那儿(您甚至从命令行说到它是echo正确的位置).您是否在与echo相同的终端上运行了node?我唯一想到的其他问题是,如果您没有重新启动终端,或者您在修改~/.bash_profile之后或者正在某个地方出现简单的错字之后就没有运行服务器.

As far as everything else, it sounds like PORT should be there (you even said it was properly echo-ing from command line). Did you run node out of the same terminal as you used echo? The only other issues I can think of are if you didn't restart the terminal you're running your server out of after you modified your ~/.bash_profile, or maybe a simple typo somewhere.

我本来可以将此作为评论发表,但是我没有分数.

I would have posted this as a comment, but I don't have the score for it.

这篇关于process.env变量即使在导出后也未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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