What does this mean: "executes the handler for the first match"

Tell us what’s happening:
So I just completed Serve an HTML File, but I’m a bit confused on the Note at the bottom of the lesson. What does “executes the handler for the first match” mean? I can see that if the there are two routes in the get function I only see the first one. But I’m not sure why? Is it because the action of going to the website just sends one request and if there was a way to send two requests the second route would act? That doesn’t sound right to me though? What’s a good way to dive into more detail about this nuance?
Basically, I understand that because I have two routes (am I using that word correctly) below that I will only see the first but I don’t understand what “executes the handler for the first match” means because the HANDLER has the both routes in it right?

Your code so far
var express = require(‘express’);

var app = express();
var absolutePath = __dirname + "/views/index.html"
console.log("Hello World");
app.get('/',(req,res) => {
	res.send("Hello Express");
	res.sendFile(absolutePath);
});

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.74 Safari/537.36

Challenge: Serve an HTML File

Link to the challenge:

If you have two handlers for the same path the one that comes first in the code will be executed while the other will not, but express provides the next param just for this reason.

If you have more than one handler for the same path, and you want them both called the one that is higher up in the code must call next.

I’ll give an example where the second handler will never be executed:

app.get('/', (req, res, next) => { 
    console.log('request received ');  
})

app.get('/', (req, res, next) => { 
    console.log('2nd handler not executed ');  
})

Here you have two handlers for the same path, but the 2nd one will never be executed as the first does not call next, to have the 2nd one executed we can make a small change:

app.get('/', (req, res, next) => { 
    console.log('request received ');  
    next();
})

app.get('/', (req, res, next) => { 
    console.log('2nd handler executed');  
})
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.