javascript - App not running on port defined in .env file | NodeJS - Stack Overflow

Following is my code -apps.jsconst express = require('express');const app = express();con

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.

Share Improve this question asked Apr 6, 2022 at 6:52 NeshNesh 2,5819 gold badges40 silver badges56 bronze badges 1
  • 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
Add a ment  | 

1 Answer 1

Reset to default 8

You 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745183014a4615507.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信