简体   繁体   中英

port undefined run by npm run start

I write following code in 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. Why the program run by nodemon the value of the port variable is undefined?

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. Write the port value in

port=8080

install the dotenv from npm

npm install dotenv

add the this line before define port variable

require('dotenv').config()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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