Home > other >  Why errorHandler middlewear is getting called 2 time in express?
Why errorHandler middlewear is getting called 2 time in express?

Time:10-07

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?

CodePudding user response:

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");
})
  • Related