Home > database >  Middleware being executed even after respnse being sent
Middleware being executed even after respnse being sent

Time:06-24

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.

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

CodePudding user response:

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

  • Related