ChatGPT解决这个技术问题 Extra ChatGPT

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);
1) A port is required by .listen(), so you shouldn't try going without. 2) Are you getting any errors when running the application? Or does it just seem inaccessible from a browser? 3) Are you trying to access the website on the same machine with localhost:3000, localhost:3001, etc.? If you're using two machines, one client and one server, you'll need to add exceptions to the firewall on the server to allow Node to receive requests from the client.
How are you launching the app?
Any chance you can put a scrubbed/sanitized version up in a gist?
@Jonathan Good to know about .listen(). Above when I say, "the app runs", this is the same as you saying, "no errors when running the application". When I say, "web page does not load", this is the same as you saying, "inaccessible from a browser". All access from the same machine (my server). Thanks for the feedback.
@deitch I'm using $ supervisor app.js or $ PORT=[PORT] node app.js when I want to set the environment port variable. I'll put up a code sample.

E
EhevuTov

The following works if you have something like this in your app.js:

http.createServer(app).listen(app.get('port'),
  function(){
    console.log("Express server listening on port " + app.get('port'));
});

Either explicitly hardcode your code to use the port you want, like:

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

This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.

Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.

$ PORT=8080 node app.js

In reference to your code example, you want something like this:

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

// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);

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);
app.listen(app.get('port'));

This is really weird. I have done the following: 1. Put the app.set() code inside my app and changed 3000 to 8080. Still only works on app.listen(3000). 2. Change the environment port variable to 8080 when running the node app. Still only works on app.listen(3000). 3. Gone to /usr/bin/express (line 220) and changed 3000 to 8080. Still only works on app.listen(3000). Thank you for the informative post though. Is there something I need to restart? Express can't be restarted from what I can tell and restarting the Node app happens every time I use node app.js.
@BenjaminMartin Express is just a module like any other module, so just a simple node app.js will start it (I personally use nodemon when developing and testing. What you might be thinking of is the express command-line executable that is a helper process that builds out your skeleton file structure. Can you post a gist of your code?
gotcha. I usually only use nodemon in conjunction with nohup to keep my app running indefinitely. I'm not using the CL executable version of express so it must be restarting every time I restart my node app. See my original post for an edit with code. Thanks!
@BenjaminMartin check the bottom of my answer and run that code. That should work just fine. I just tested it on my machine.
This is another useful way to change the port but it still only works when the port is 3000. I'm starting to wonder if there's something on my server that only allows content to be served on certain ports. I have no idea where this configuration would be located though. Could this be an issue? FYI I'm running Ubuntu 10.04.
L
Larry Lu

In bin/www, there is a line:

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

Try to modify it.


I tried setting the port in app.js but this line was overriding. This is the correct place to change the port.
C
C B

Try this

$ PORT=8080 node app.js

Thanks for the answer - this only works if I have app.listen(3000) set inside app.js. In other words, setting the port when I run the app as you have done doesn't seem to override app.listen().
Perfect. I use is with express: PORT=8000 npm start. So you can use whatever you want :D.
A
Abhishek Gautam

https://i.stack.imgur.com/oEtEf.png

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


A
AliAvci

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


u
user3711307

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


A better option to run your app on a port below 1024 is to forward a port with greater number. Using sudo to be able to access a port number lower than 1024 is generally considered bad practice.
u
user1276682

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.


u
user2855232

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!


That's what worked for me. Forgot to allow the port.
d
dinigo

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>

M
MEAbid

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


C
Community

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


M
Mark Longmire

In app.js, just add...

process.env.PORT=2999;

This will isolate the PORT variable to the express application.


w
williamli

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.


single hyphen -p didn't worked for me. But double hyphen --p working. Thanks for this answer.
S
Shreeparna Sarkar

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


h
huckbit

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


S
Samuel Adranyi

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


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now