admin管理员组文章数量:1415491
Following is my code -
apps.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
.env file
PORT=8000
Now when I run the program though terminal via mand - node app.js
I am getting -
Server running on port: 3000
but I want it to run on 8000 and pick it from .env file. Let me know what I am doing wrong here.
I know while running from terminal I can define PORT=8000
or app.set()
but I am looking to pick it from an environment file. Let me know what I am doing wrong here / in terms of understanding.
Following is my code -
apps.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
.env file
PORT=8000
Now when I run the program though terminal via mand - node app.js
I am getting -
Server running on port: 3000
but I want it to run on 8000 and pick it from .env file. Let me know what I am doing wrong here.
I know while running from terminal I can define PORT=8000
or app.set()
but I am looking to pick it from an environment file. Let me know what I am doing wrong here / in terms of understanding.
- 2 But you're not importing your .env file in your app at all. Use dotenv – Jeremy Thille Commented Apr 6, 2022 at 6:55
1 Answer
Reset to default 8You can use dotenv
npm package for custom environment variables.
Usage
Create a .env
file in the root of your project:
PORT=8000
As early as possible in your application, import and configure dotenv:
require('dotenv').config();
// Your .env variables is now available in process.env object
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/users', (_req, res) => {
res.send('Hello World');
})
app.listen(PORT, () => {
console.log(`Server running on port: `, PORT);
});
Read more in the official package: dotenv
本文标签: javascriptApp not running on port defined in env fileNodeJSStack Overflow
版权声明:本文标题:javascript - App not running on port defined in .env file | NodeJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745183013a2646554.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论