So I was working in Node, Express and connecting to MongoDB.
I am using Nodemon to watch for changes.
All was well until I installed create-react-app.
My file structure is
root
|
| - backend
| | - server.js
|
| - frontend //react app lives here
| | - src
| ...
When I cd into the backend folder and start the server I get this error:
node:events:491
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied 4000;
at Server.setupListenHandle [as _listen2] (node:net:1415:21)
at listenInCluster (node:net:1480:12)
at Server.listen (node:net:1579:5)
at Function.listen (C:\Users\Owner\Desktop\Learning JS\Backend\teachers-pet\backend\node_modules\express\lib\application.js:635:24)
at C:\Users\Owner\Desktop\Learning JS\Backend\teachers-pet\backend\server.js:13:13
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1459:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '4000;',
port: -1
}
[nodemon] app crashed - waiting for file changes before starting...
My server.js file:
const dotenv = require('dotenv');
const express = require('express');
const mongoose = require('mongoose');
dotenv.config();
const app = express();
app.use(express.json());
app.use(express.json());
console.log(process.env.PORT);
const PORT = process.env.PORT || 8000;
mongoose.connect(process.env.MONGO_URI)
.then(()=>{
app.listen(PORT, () => {
console.log('connected to db & listening on port 4000');
})
})
.catch(err => console.log(err));
If I type out app.listen(4000 , () => {...})
server runs. But when I include the PORT variable or write out process.env.PORT
it crashes.
When I console log process.env.PORT
it logs the correct port number.
Even when I use the ||
operator it should switch to the specified port, but it still wouldn’t !
Why is this happening? Am I missing something that I should be aware of?
TIA