Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript - app.set('port', 8080) versus app.listen(8080) in Express.js

Tags:

I've been trying to use Express.js to launch a website. At first, I was using app.set('port', 8080) but the browser was unable to connect to the page. Afterwards, I changed the code to app.listen(8080) and the webpage appeared normally.

This led me to wonder, what is the difference between these two functions?

like image 863
peco Avatar asked Aug 16 '14 05:08

peco


2 Answers

app.set('port', 8080) is similar to setting a "variable" named port to 8080, which you can access later on using app.get('port'). Accessing your website from the browser will really not work because you still didn't tell your app to listen and accept connections.

app.listen(8080) on the other hand listens for connections at port 8080. This is the part where you're telling your app to listen and accept connections. Accessing your app from the browser using localhost:8080 will work if you have this in your code.

The two commands can actually be used together:

app.set('port', 8080);
app.listen(app.get('port'));
like image 188
Arnelle Balane Avatar answered Sep 22 '22 18:09

Arnelle Balane


It is simple enough to declare a variable server at the bottom of the page and define the port that you want. You can console.log the port so that it will be visible in the command line.

var server = app.listen(8080,function(){
   console.log('express server listening on port ' + server.address().port);
    })
like image 28
Winnemucca Avatar answered Sep 21 '22 18:09

Winnemucca