Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Middleware being executed even after respnse being sent

I was wrting very basic express code

const express = require('express');

const app = express();

app.use('/willgo', (req, res, next) => {
    console.log('In a middleware');
    next();
})

app.use('/notgo', (req, res, next) => {
    console.log('In another middleware');
    res.send('<h1> Inn intermediate </h1>');
    res.end();
})

app.use('/', (req, res, next) => {
    console.log('In final middleware');
    res.send('<h1> Inn final </h1>');
})

// const server = http.createServer((req, res) => {
// server.listen(2001);

app.listen(3002);

On localhost:3002/notgo the console is

In another middleware
In final middleware

It shows that the last middleware executed, even though I have already sent the request.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is this the deafult behavior or I am missing something because res.send() is supposed to finish the processing.

>Solution :

Loop,

res.end(); will finish the response. But does this code need to be middleware or plain endpoints?

Then you should use app.get();

The console output ‘In final middleware’ is probably because the browser wants to load a favicon.ico from the root, which will call app.use(‘/’, …. )

If you would do a curl / invoke web request from the cli you would see that there is only one console output.

on windows 10/11: (iwr http://localhost:3002/notgo).content

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading