I know this error has been asked a million times but I believe that the answers are not the correct ones or are not the most efficient.
// import all libraries
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const app = express();
require('dotenv').config();
// setup connections
mongoose.connect(process.env.MONGODB_URL)
.then(() => console.log("Connected to DB 🔌"))
.catch(() => console.log("Couldn't connect to db ❌"));
// setup middlewares
app.use(cors()); // CORS => Cross origin resource sharing; // share frontend <-> backend
app.use(express.json());
// setup routes
app.use("/api/auth", require("./routes/user"));
app.use("/api/books", require("./routes/book"));
app.use("/api/rentals", require("./routes/rental"));
// start listening on server
const port = process.env.PORT;
app.listen(port, () => {
console.log("Server running...");
})
There is my code for reference. If I change the port from 5000 to 5500 in the .env it all works fine. If I deactivate the air play port, it all works fine.
My problem is that when I run a dotnet api server IN PORT 5000 there is NO error.
Why can I run a dotnet server in 5000 with no problem but in node it gives me an error?
I ran lsof -i tcp:5000 meanwhile running my dotnet api:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
firefox 938 arturofiliovilla 137u IPv4 0x23e78a2a111d8441 0t0 TCP localhost:59093->localhost:commplex-main (ESTABLISHED)
ControlCe 25701 arturofiliovilla 21u IPv4 0x23e78a2a108e4ed1 0t0 TCP *:commplex-main (LISTEN)
ControlCe 25701 arturofiliovilla 22u IPv6 0x23e78a1babf17ce9 0t0 TCP *:commplex-main (LISTEN)
API 26565 arturofiliovilla 238u IPv4 0x23e78a2a12ba39b1 0t0 TCP localhost:commplex-main (LISTEN)
API 26565 arturofiliovilla 239u IPv6 0x23e78a1babf09189 0t0 TCP localhost:commplex-main (LISTEN)
API 26565 arturofiliovilla 241u IPv4 0x23e78a2a10910ed1 0t0 TCP localhost:commplex-main->localhost:59093 (ESTABLISHED)
Maybe there is a masking? I'm not sure but I have no errors with my dotnet server.
Any ideas why this is happening?
[::]:5000
and/or 0.0.0.0:5000
by default, when you only specify port 5000. That's why a conflict occurs.localhost:5000
.If you read a little bit more about computer networking, you will see how huge the differences are between the two binding approaches.
You can try to ask Express to bind to localhost:5000
, aka
app.listen(port, "localhost", () => {
console.log("Server running...");
})
References