The flow of Express middleware

Imagine you have the following setup for an Express app:

const express = require('express')

const app = express()

app.use((req, res, next) => {
  console.log('\n\nALWAYS')
  next()
})

app.get('/a', (req, res) => {
  console.log('/a: route terminated')
  res.send('/a')
})

app.use((req, res) => {
  console.log('route not handled')
  res.send('404 - not found')
})

app.listen(3000, () => {
  console.log('listening on 3000')
})

If you were to visit /a, the console would show:

ALWAYS
/a: route terminated


ALWAYS
route not handled

It might be confusing to see an extra middleware log. You might have expected only two lines of console output like this:

ALWAYS
route not handled

Can someone explain why that additional middleware log showed up unexpectedly?

Answer №1

This scenario is a common source of confusion for many people. The issue likely arises when you navigate to /a in your web browser, triggering two separate requests. One request is made for the specific page /a, while the second request is for the favicon icon associated with the website (which browsers fetch to display as a visual representation of the site).

To gain clarity on what's happening, consider logging the URL of each request in both your middleware and 404 error handler:

const express = require('express')

const app = express()

app.use((req, res, next) => {

  console.log('\n\nRequest for: ', req.url);
  next();
})

app.get('/a', (req, res) => {
  console.log('/a: route completed')
  res.send('/a')
})

app.use((req, res) => {
  console.log('route not supported for ', req.url);
  res.send('404 - Page Not Found');
});

app.listen(3000, () => {
  console.log('server listening on port 3000')
})

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

Ways to transform node js request

Is it possible to customize the requested URL in Node.js? http://localhost/user/add When the request reaches the server, I want to append 'api' to my current request, like this: http://localhost/api/user/add I tried implementing a middleware ...

Is it advisable to utilize a NodeJS global for accessing configuration properties within my application?

Allow me to pose a straightforward question: Within NodeJS, there exists the option to define globals using GLOBAL.myConfigObject = {...} I am curious about the opinions of the developer community on whether this method is considered best practice. If n ...

Transferring information from a React application to a Node Express server

I'm having issues passing data from my React frontend to my Node/Express server using the onSubmit function. The data is not displaying in the console or on the page, and it simply shows up as "undefined." Can someone provide some assistance? App.js ...

Is there a way to retrieve user information in Next.js using auth0 getSession() from a middleware function, or are there alternative methods to achieve this with middleware?

Here's the code snippet from my /pages/api/_middleware.js file: import { getSession } from '@auth0/nextjs-auth0' export default async function middleware(req, ev) { const session = await getSession(req) console.log(session) retu ...

Having trouble fetching data (node.js) from my client (react.js)

I'm experiencing difficulty retrieving the data I send from the client to the server. Below is my react code: axios.post('http://localhost:5000/post-entry', { data: formData }) .then(res => { console.log(res); }) This is my server cod ...

Nodejs does not automatically redirect to https connections

Currently, I have set up a node server with express on top. My domain registrar is GoDaddy. When trying to connect using www.example.com, it doesn't work, but it works fine with https://www.example.com. Below is the code snippet for reference: app.u ...

Are there any alternatives in NodeJS similar to PyAutoGUI that have the ability to search for an image within a screenshot?

I've been working on developing a bot to automate tasks in a video game using JS and Node, primarily utilizing RobotJS. However, I'm encountering an issue where I need to locate and click on a moving element on the screen, similar to PyAutoGUI&ap ...

Convert image buffer to string using Mongoose getter?

I have developed a basic node backend application modeled after eBay. I am now working on creating a react frontend app to complement it. Within the app, users can list items for sale and include a photo with their listing. The item information is stored ...

Tips for utilizing UTC time in defining models with Prisma.js and in general in an Express.js project

Is there a way to Run the node.js project in UTC instead of the local timezone? and How can I specify UTC time when defining a model with prisma.js? model Profile { CreatedDate DateTime @default(now()) // but I need it in UTC ModifiedDate DateTi ...

Ways to showcase pictures stored in MongoDB gridFS

I have been working on developing a webApp that allows users to upload images, and in order to accomplish this task I am utilizing gridfs. I have managed to successfully save the images, but I encounter difficulties when it comes to displaying them. In o ...

Exploring the Integration of Callbacks and Promises in Express.js

I'm currently developing an Express.js application where I am utilizing x-ray as a scraping tool to extract information. For each individual website I scrape, I intend to establish a unique model due to the distinct data and procedures involved in th ...

Socket.io requires two connections from the server in order for the first one to respond

I am experimenting with creating a private chat (or group chat) using socket io. To test the concept, I created an array called "person" which includes the username and the room they should join. The checks for existing users are currently absent but may b ...

Missing configuration in the file: Loggregator end point for Bluemix CF App

I'm having an issue with tailing the logs of my deployed app in Bluemix. Even though I successfully deploy it using bx app push [app-name], I encounter this error message: Warning: unable to tail logs The configuration file is missing the Loggregator ...

The command 'ng' for Angular is not being detected as a valid internal or external command, executable program, or batch file, preventing access to the Angular app from outside the localhost

Whenever I try to run "'ng' is not recognized as an internal or external command, operable program or batch file." with ng serve --host 0.0.0.0 from my command prompt, it gives me this error message. However, running it through the node.js comma ...

Restricting access to my API to only permit communication with my designated front-end application

Currently working on developing a node/express backend and looking to establish an API that is exclusively compatible with my reactjs frontend (private API). Let's take the example of an e-commerce platform where users can browse products, make selec ...

The SSE functionality is effective in a local environment, but encounters issues when deployed on Vercel's

Operating a proxy server, I send a request to OpenAI which responds with a Readable Stream object. The proxy server then redirects these events back to the client. While my code functions properly on a local deployment, it encounters issues when deployed ...

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

Leveraging Spotify's webAPI to listen to a randomly selected album by a specific artist (ID

Welcome to my little project! As I am not a developer myself, please bear with me for any silly questions that may arise. My idea is to create an "audio book machine." The concept involves using a website that showcases various artists of audiobooks. Upo ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Why does the MEAN Stack continue to route using the '#' symbol in the URL?

Currently navigating the realm of back end development. Started off by following a guide on express from thinkster. In need of some clarification. Initially, I grasped that front-end and back-end routing serve different purposes. Front-end routing relates ...