设置环境变量以在express node.js中动态更改端口

我在服务器上运行了一个index.js应用程序,该应用程序可在端口3000上运行,并且我正在通过环境变量对其进行更改,但仍无法正常工作。我正在尝试遵循一个教程,上面写着。

 1- Create an environment variable for port or run default 3000 port.
 2- Pass that variable to to app.listen()
 3- Set port=5000

但是端口没有改变,仍然保持3000。它无法将端口设置为5000。

index.js的代码在这里:

//index.js
const express = require('express');
var app = express();
app.get('/',(req,res)=>{
    res.send('Hello World!!!');
});
const port = process.env.PORT || 3000 ; 
app.listen(port,() => console.log('listening on port ' + port));

端子的输出如下:

//terminal
PS F:\node practical\Restful APIs\express-demo> set PORT=5000
PS F:\node practical\Restful APIs\express-demo> nodemon index.js
[nodemon] 1.19.4
[nodemon] to restart at any time,enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json  
[nodemon] starting `node index.js`
listening on port 3000[enter image description here][1]
chenzhao5001 回答:设置环境变量以在express node.js中动态更改端口

您可以使用dotenv软件包从环境文件动态设置端口。

安装后(npm i dotenv),如果您的主文件(index.js或app.js)在第一行中像这样使用它

require("dotenv").config();

然后,您需要在app的主文件夹中创建一个.env文件,内容如下:

PORT=5000

您的process.env.PORT将为5000。

本文链接:https://www.f2er.com/3144890.html

大家都在问