[javascript] Node.js/Express.js App Only Works on Port 3000

I have a Node.js/Express.js app running on my server that only works on port 3000 and I'm trying to figure out why. Here's what I've found:

  • Without specifying a port (app.listen()), the app runs but the web page does not load.
  • On port 3001 (app.listen(3001)) or any other port that is not in use, the app runs but the web page does not load.
  • On port 2999, the app throws an error because something else is using that port.
  • On port 3000, the app runs and the web page loads fine.

I know that Express apps default to port 3000. But strangely, my app only runs when I explicitly make it run on port 3000 (app.listen(3000)).

I found this on line 220 of /usr/bin/express:

app.set(\'port\', process.env.PORT || 3000);

Which is doing as previously stated: setting the port to what is specified or to 3000 if nothing is specified.

How could I make my app work on a different port such as 8080 or 3001?

Thanks!

Edit: Code Sample (Very Simple Node/Express App)

var express = require("express");
var app = express();

app.get('/', function(req, res){
    res.send('hello world'); 
});

// Only works on 3000 regardless of what I set environment port to or how I set [value] in app.set('port', [value]).
app.listen(3000);

This question is related to javascript node.js configuration express port

The answer is


Try this

$ PORT=8080 node app.js

If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig. Check if that is the case.


In bin/www, there is a line:

var port = normalizePort(process.env.PORT || '3000');

Try to modify it.


In app.js, just add...

process.env.PORT=2999;

This will isolate the PORT variable to the express application.


I am using the minimist package and the node startup arguments to control the port.

node server.js --port 4000

or

node server.js -p 4000

Inside server.js, the port can be determined by

var argv = parseArgs(process.argv.slice(2))

const port = argv.port || argv.p || 3000;
console.log(`Listening on port ${port}...`)

//....listen(port);

and it defaults to 3000 if no port is passed as an argument.

You can then use listen on the port variable.


The line you found just looks for the environmental variable PORT, if it's defined it uses it, otherwise uses the default port 3000. You have to define this environmental variable first (no need to be root)

export PORT=8080
node <your-app.js>

The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.

There, you will find a line such as the following

var port = normalizePort(process.env.PORT || '3000');

Change the value 3000 to any port you wish.

This is valid for Express version 4.13.1


Refer to this link.

Try to locate the bin>www location and try to change the port number...


Answer according to current version of express

If you talk about the current version of express, if you run app.listen() to start listening without specifying port, Express will chose a random port for your application, to find out about which port it is currently running on use

app.listen(0, () => {
    console.log(app.address().port)
}

should output the port of your app. Moreover that first parameter 0 can be totally ignored but is not recommended


Noticed this was never resolved... You likely have a firewall in front of your machine blocking those ports, or iptables is set up to prevent the use of those ports.

Try running nmap -F localhost when you run your app (install nmap if you don't have it). If it appears that you're running the app on the correct port and you can't access it via a remote browser then there is some middleware or a physical firewall that's blocking the port.

Hope this helps!


Just a note for Mac OS X and Linux users:

If you want to run your Node / Express app on a port number lower than 1024, you have to run as the superuser: sudo PORT=80 node app.js


I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.

Just install the package with the command:

npm install dotenv

require it on your application:

require('dotenv').config()

Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000

PORT=5000

and that's it.

More info here


Make sure you are running from that folder of your application, where you have the package.json.


In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www. I just changed the statement in bin/www.


If you want to show something you're connected on 3000

var express = require('express')
var app = express()

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

I hope that will be helpful to you


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to configuration

My eclipse won't open, i download the bundle pack it keeps saying error log Getting value from appsettings.json in .net core pgadmin4 : postgresql application server could not be contacted. ASP.NET Core configuration for .NET Core console application Turning off eslint rule for a specific file PHP Warning: Module already loaded in Unknown on line 0 How to read AppSettings values from a .json file in ASP.NET Core How to store Configuration file and read it using React Hadoop cluster setup - java.net.ConnectException: Connection refused Maven Jacoco Configuration - Exclude classes/packages from report not working

Examples related to express

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block jwt check if token expired Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] npm notice created a lockfile as package-lock.json. You should commit this file Make Axios send cookies in its requests automatically What does body-parser do with express? SyntaxError: Unexpected token function - Async Await Nodejs Route.get() requires callback functions but got a "object Undefined" How to redirect to another page in node.js

Examples related to port

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated How do I kill the process currently using a port on localhost in Windows? Node.js Port 3000 already in use but it actually isn't? Can't connect to Postgresql on port 5432 Spring Boot - How to get the running port Make docker use IPv4 for port binding How to change the default port of mysql from 3306 to 3360 Open firewall port on CentOS 7 Unable to launch the IIS Express Web server, Failed to register URL, Access is denied XAMPP Port 80 in use by "Unable to open process" with PID 4