简体   繁体   English

端口未定义由 npm 运行开始

[英]port undefined run by npm run start

I write following code in nodeJS:我在 nodeJS 中编写了以下代码:

const port = process.env.port;
const app = express();
const routes = require('./routes/routes');
app.use('/', routes);
app.listen(port, console.log('your browser run on port ' + port));

when i run code by nodemon(npm run start), port variable is undefined while when i run it with node(node app.js), the port variable contains the value of the port where the program is running.当我通过 nodemon(npm run start) 运行代码时,端口变量是未定义的,而当我使用节点(node app.js) 运行它时,端口变量包含程序正在运行的端口的值。 Why the program run by nodemon the value of the port variable is undefined?为什么nodemon运行的程序端口变量的值未定义?

Export the port beforehand.预先导出端口。

export port=8080

Additionally, use some fallback.此外,使用一些回退。

const port = process.env.port || "3000"

Also note, by convention, environment variables are upper cases.还要注意,按照惯例,环境变量是大写的。

export APP_PORT=8080
const port = process.env.APP_PORT || "3000"

If you don't have.env file create one.如果您没有 .env 文件,请创建一个。 Write the port value in写入端口值

port=8080

install the dotenv from npm从 npm 安装 dotenv

npm install dotenv

add the this line before define port variable在定义端口变量之前添加这一行

require('dotenv').config()

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

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