terminal after trying to run server server
const express = require('express')
const colors = require('colors')
const dotenv = require('dotenv').config()
const {errorHandler} = require('./middleware/errorMiddleware')
const connectDB = require('./config/db')
const port = process.env.PORT || 5000
connectDB()
const app = express()
app.use(express.json())
app.use(express.urlencoded({extended: false}))
app.use('/api/goals', require('./routes/goalRoutes') )
app.use(errorHandler)
app.listen(port, () => console.log(`Server started on port ${port} `) )
There is already an application listening on port 5000, like the error message suggests. Close any other command prompt/bash that may be running an instance of the application and try again.
Port 5000 is already in use by another application. Either close this port or choose an unused port by:
Changing: const port = process.env.PORT || 5000 to const port = process.env.PORT || <otherport>
or by providing an unused port as an environmental variable.
Related
I am having a NodeJS application with some basic routes and sql server connectivity. I am using pkg for the executables. All the configuration settings are stored on .env file. When I am trying to run multiple instance of the application from different directories with different port number specified in the .env file, my app is crashing with "EADDRINUSE" error code and says the particular port is used. I am able to run only single instance of application with any defined port number in .env file. I didn't explicitly use any default port number in the application.
"use strict";
const express = require("express");
const mac = require("./auth/auth");
const ejs = require("ejs");
var log = require('./utils/scroll');
var bodyParser = require("body-parser");
const app = express();
app.use(require('./utils/init'));
app.use(bodyParser.urlencoded({ extended: true, limit: "500mb"}));
app.use(bodyParser.json({limit: "500mb"}));
app.use(require('./utils/cors'));
app.use('/',require('./routes'));
console.log(mac);
var port = (process.env.port);
log();
app.use("/", express.static("assets"));
app.set("view engine", "ejs");
app.listen(port,()=>{
console.log("Server Running at Port :", port);
});
Is there any other setting I have to do?.
I had tried configuring different .env files with different port numbers per application.
The port your express app will be using is the one defined by process.env.port which I assume comes for your .env file.
You need handle the case the port is already in use to automatically change the port number and try again.
Something like that:
const express = require("express");
const app = express();
app.portNumber = 3000;
function listen(port) {
app.portNumber = port;
app.listen(port, () => {
console.log("server is running on port :" + app.portNumber);
}).on('error', (err) => {
if(err.code === 'EADDRINUSE') {
console.log(`----- Port ${port} is busy, trying with port ${port + 1} -----`);
listen(port + 1)
} else {
throw err;
}
});
}
listen(app.portNumber);
Check this post for a more complete answer: https://stackoverflow.com/a/53110778/5103610
I've just started learning node.js but when I try to launch the hello world code by writing on the terminal node server.js, localhost:3000 gives me the following error:
This page isn’t working;
localhost didn’t send any data.
ERR_EMPTY_RESPONSE
I've been searching for 2h now and I've found nothing. I've checked the port 3000 in cmd with netstat -a -n -o and it says that the port is listening (so I guess it is working). So what is preventing me from accesing to that port.
Here it my JS files:
server.js:
const http = require('http');
const app = require('./app');
const port = process.env.PORT || 3000;
const server = http.createServer();
server.listen(port);
app.js:
const { request } = require('express');
const express = require('express');
const app = express();
app.use((req, res, next) => {
res.status(200).json({
message: 'It works'
});
})
module.exports = app;
Add the required app to the createServer call:
const server = http.createServer(app);
In this way the http server can route your http requests to it.
Could process.env.PORT be set somewhere, causing your app to be hosted on that port instead?
An easy way to check would be to console.log the PORT variable in your script, and see if it has any value.
If it does have a value, trying going to localhost:PORT
I am trying to build a full stack app using ReactJS for the frontend and ExpressJS for the backend. I use Axios to make calls from my frontend to my backend. When I make those calls, I get these errors:
My express index file:
const express = require('express')
const path = require('path')
var app = express()
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
My get call from React frontend:
componentDidMount() {
axios.get("http://localhost:5000/servers.json").then((res => {
this.setState({ servers: res.data })
}))
}
React server is running on port 3000 and Express server is running port 5000, so there shouldn't be a conflict there...
The reason you are getting the error http://localhost:3000 is not allowed by Access-Control-Allow-Origin is because of the same origin policy, a security feature that's restricting your react script from accessing/communicating your server since they are from different origins. Please note that for documents or scripts to be considered as having the same origin they need to have the same protocol (e.g http / https), hostname (e.g localhost / www.my-server.com) and port. In your case port the react script runs at port 3000 while the express script is running on port 5000, thus the error.
To solve this, you need to enable CORS - Cross Origin Resource Sharing on your server side code. First install the cors dependency using the command
npm install cors
Then update the code in your server to look as follows:
const express = require('express')
const path = require('path')
const cors = require('cors')
const app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
Hopefully this works for you.
This looks like a basic cors issue. Add this cors middleware to your express server. It's the state of the art solution to this problem.
const express = require('express')
const path = require('path')
var cors = require('cors')
var app = express()
app.use(cors())
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`)
})
app.use(express.static(path.join(__dirname, "public")))
If you are interested about cors in general, check out the wikipedia page.
I'm trying to get socket.io working on my heorku app, but I think I'm having some trouble defining the ports. On the backend I have my express app listening to the process.env port or 5000, and I have my socket.io port listening on 8000.
Node.js
const express = require("express");
const app = express();
const server = require('http').Server(app)
const io = require('socket.io')(server)
const socketPort = 8000;
io.listen(socketPort);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port} !`));
And on my front end I have my socket to route requests to localhost:8000
Reactjs
const socket = io('http://localhost:8000')
//Open connection to backend
socket.on('connect', ()=>{
console.log("Connected");
})
It works just fine when I run it locally, but I can't get it working on Heroku - GET http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MszLUDm net::ERR_CONNECTION_REFUSED
Is there a specific way I need to set up these ports? As far as I know I can only set up one process.env port. Should I be subbing something into the "localhost:8000" on the front end?
Thanks!
On the client side I ended up just declaring the socket like this:
const socket = io();
Leaving out the localhost:5000 part altogether.
I have been struggling to find the source of an error in the following code:
const express = require("express");
const path = require("path");
const WebSocket = require("ws");
const SocketServer = WebSocket.Server;
const PORT = process.env.PORT || 3000; // port to listen on
const INDEX = path.join(__dirname, "index.html"); // index address
var server = express();
server.use((req, res) => res.sendFile(INDEX));
server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));
const wss = new SocketServer({server}); // wss = web socket server
(I have code below for connection etc. that is irrelevant to this question I think)
Upon running this, I receive the following error from the client in the browser:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
What is confusing me is that the code works if I make the following change:
var server = express()
.use((req, res) => res.sendFile(INDEX));
.listen(PORT, () => console.log(`Listening on port ${ PORT }`));
The problem with this method is that it does not work to add in another .use before the existing .use, which is necessary for accessing static files (i.e. javascript as its own file instead of in an HTML file)
Why does changing my code between these two examples break it? What can I do to resolve this?
Thank you
You need to pass the http.createServer instance to the WebsocketServer. Not express instance
var app = express();
var server = http.createServer(app);
I found a solution!
It turns out that you must set the value of the server variable when .use and .listen are called.
var server = express();
server = server.use((req, res) => res.sendFile(INDEX));
server = server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));
instead of
var server = express();
server.use((req, res) => res.sendFile(INDEX));
server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));