What could be causing the errorHandler middleware to be triggered twice in an express application?

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

After accessing localhost:8000 in NodeJS, the message "error handled" gets printed twice in the terminal. It would be helpful if someone could provide an explanation for this occurrence.

Answer №1

When you access localhost:8000 in your web browser, it will not only load http://localhost:8000/ but also http://localhost:8000/favicon.ico due to default browser behavior.

Since middleWear1 is configured to run for every request and both requests are sent to the server, "error handled" will be printed twice in the console.

To address the question raised in the comment:

If you only want middleWear1 to run for the / route and not all requests, you can use the following code:

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 occurred at server")
}

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on creating a Google function using Twilio to automatically send an SMS when there is a change in the Realtime database

I am currently working on my first Google Cloud Function and I have limited knowledge about it. My goal is to create a Google Cloud Function integrated with Twilio. Whenever the water level changes in my Realtime Database, I want to send an SMS to a specif ...

Comparing Node version with outdated npm packages

A few months back, I went ahead and installed node 10.15.3 on my system followed by an upgrade to npm 6.9.0. Ever since the update, I've been noticing some irregularities and now I am looking to revert back to the previous version of npm. These were ...

The Art of Redis Pub/Sub: A Blueprint for Successful Design

Our system heavily relies on socket i/o for real-time data exchange. Users interact with the application through sockets, but due to our use of a load balancer, we can't utilize socket i/o's namespace model. Instead, we have opted to use redis&ap ...

What strategies can be used to efficiently perform Asynchronous Operations on a high volume of rows in a particular database table?

I am looking to perform Asynchronous Operations on every row of a specific database table, which could potentially contain 500,000, 600,000, or even more rows. My initial approach was: router.get('/users', async (req, res) => { const users = ...

Trouble with request ordering in POST method with Node.js and Postman

Currently, I am diving into the world of node.js and leveraging Postman to handle requests with parameters in the request body. When it comes to setting up the router: router.post('/locations', ctrlLocations.locationsCreate); below is a glimpse ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Troubleshooting: Struggling to Upload Image using Firebase-Admin

I'm currently trying to write a simple code for uploading an image to Firebase using Firebase-Admin (NOT firebase), NodeJS, Express & Multer, but unfortunately, it just won't work no matter what I try. Here's the snippet of my code: con ...

Loop through an array of objects in Node.js using ng-repeat

I have integrated angularJS with a node back-end that transmits data using socketio. When I attempt to display the data using ng-repeat, I encounter an issue. If I set the initial data within the controller, ng-repeat functions properly. However, if I add ...

Encountering 'npm install' error while trying to follow the Angular2 5 minute

I encountered an error while attempting to follow the Angular2 5 min quick start guide. Can someone assist me in resolving it? vagrant@vagrant-ubuntu-trusty-64:/vagrant/angular2-tutorial$ sudo npm install <a href="/cdn-cgi/l/email-protection" class=" ...

Is there a way to modify the route or file name of the index.html file in a React project?

Every time I use npm build to create a React app (using the typical react-scripts/create-creact-app, etc.), the entry file always ends up in build/index.html. I attempted to move the src folder into a subfolder, but unfortunately, index.js must remain in ...

Is there a way to include app.use middleware in all of my files automatically?

Recently, I have developed a simple express js application. After configuring routes and other necessary components, I included app.use('/api/', require('./api/api.js')); in my code. The contents of api.js are as follows: var express ...

Is there a way to convert the items in the products variable into the more comprehensive detailedProducts?

New to JS, looking for guidance on transforming the products variable into detailedProducts in JavaScript const products = [ { title: 'Yellow Pail', submitterAvatarUrl: 'images/avatars/daniel.jpg', productImageUrl: 'images ...

APNS functionality is supported by APN providers, but it is not compatible with NodeJS in a production

I've set up a nodeJS script to send APNs. In development, it always works flawlessly. However, when I switch to production, the notifications never go through. Oddly enough, when I use the same notification ID with my production certificate in Easy Ap ...

The AJAX post request is returning an undefined value

I'm working with JavaScript, AJAX, and Node.js but I'm having trouble receiving a value on the server side when making a POST request. Despite my efforts to test it out, the console keeps returning 'value undefined'. Here's a snip ...

MongoDB table collections (table names in other databases)

After setting up my express server to connect to mongodb, I encountered an issue despite everything working fine initially. I created a collection in my mongodb called projects (plural form). In my project.model.js file, I defined the model as follows: c ...

Execute the Node.js function repeatedly within a setTimeout function, utilizing recursion and a callback

Can anyone help me understand why my attempt to recursively call a nodejs function in setTimeout with a callback is not working as intended? I have attached the code snippet below. Any guidance or suggestions would be appreciated. Model.xyz= function(cb ...

Wiki experiencing issues with NodeJS HttpGet functionality

Goal Retrieve the HTML content of a Wiki Page. Introduction In an attempt to fetch the HTML of a Wiki page () for data parsing purposes, I am utilizing NodeJS and its HTTP Request methods. Code Snippet Below is the simple code snippet that accesses th ...

Develop a mobile application utilizing reactjs based on my website, not native

I am in the process of creating a mobile application that mirrors my existing website built with reactjs. As I was researching on reactjs, I wondered if it is possible to convert my reactjs code from the website into code for the mobile application. Any s ...

How to detect a disconnected socket in Node.js using websockets

Encountering an issue with my nodejs websocket server. Upon graceful termination of client connections, the onclose method is triggered for closed sockets where I conduct clean up tasks. However, when clients disconnect due to network issues, the onclose ...

Combining React with Gulp and Babelify to create efficient and powerful

I am looking to update my application from using React and Gulp with ES5 to React + Gulp and ES6. I attempted to replace reactify with babelify, but I am encountering a gulp error: Illegal import declaration Below is my current gulpfile.js: "use strict" ...