Jodes Jodes - 3 days ago 6
Node.js Question

Node Express: does order of calls matter?

Node Express documentation gives a hello-world example:

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

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

app.listen(3000)


Does the order of
listen()
and
get()
matter? (could they be swapped?) And what would happen if
get()
and
listen()
were called a second time after the first calls as above?

Answer

Let's deconstruct the example :

app.listen(3000)

this line attaches your app to a port, in this case 3000. It enables you to access it by typing http://localhost:3000, you typically would not want to change the port you app runs on durig execution.

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

this is basically a listener, which will be called when you make a GET request to the / route. It tells your app what to answer when you type the url on your browser.

It is attached to the app object, whether the app is running or not, so it can be written before listen, after, or in another file altogether.

In the strange case where you'd have a second listener on the same route, one of them would not be executed. I suggest you test it yourself if you really want to know which takes precedence, here's a sample code :

app.get('/', function (req, res) {
  res.send('Will I be executed?')
});


app.get('/', function (req, res) {
  res.send('or maybe I will?')
});

app.listen(3000)
Comments