Why errorHandler middlewear is getting called 2 time in express?

Issue

const express = require('express')
const app = express();

function middleWear1(req, res, next) {
    throw Error()
}

function errorHandler(err, req, res, next) {
    console.log("error handled");
    res.end("error occured at server")
}

app.use(middleWear1)
app.use(errorHandler)

app.get('/', middleWear1)

app.listen(8000, () => {
    console.log("server is listening");
})

when I do localhost:8000 I get "error handled" printed two times in NodeJS terminal.

can some one explain why is it happening?

Solution

Assuming you requested localhost:8000 through your web-browser, your browser will not only load http://localhost:8000/ but http://localhost:8000/favicon.ico as well. This is default browser behaviour.

Now, since you’ve setup middleWear1 to run for every request and the two requests are sent to your server, error handled gets printed twice to the console.

To answer you question from the comment:

In order to prevent middleWear1 running for all requests and only for your / route, you can do:

const express = require('express')
const app = express()

function middleWear1(req, res, next) {
    throw Error()
}

function errorHandler(err, req, res, next) {
    console.log("error handled");
    res.end("error occured at server")
}

  
app.get('/', middleWear1) 
app.use(errorHandler)

app.listen(8000, () => {
    console.log("server is listening");
})

Answered By – eol

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published