Search code examples
node.jsexpressmiddleware

a use method of express.js called twice


I had a very simple node.js project with express.js library set up for my project. I found that the middleware implemented using express().use() was called twice when I made a request to the nodejs server.

The following is the code-snap of the express library using and implementing middleware layer.

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

app.use((req, res, next) => {
  console.log('This is a middleware layer!');
  res.send('hello from express.');
});

module.exports = app;

May I know if there was any thing going wrong? Thanks a lot.

The following screen capture shows the console.log run twice.

https://i.sstatic.net/RIs6J.png


Solution

  • Modify your middleware to log req.url so you can see what resource the request is for:

    app.use((req, res, next) => {
      console.log('This is a middleware layer!', req.url);    // Log req.url
      res.send('hello from express.');
    });
    

    Probably you will find that the browser is requesting /favicon.ico (in addition to the regular web page) to see if there's an icon to display for this web page. This is a browser-specific thing.

    This is a reason that you should generally not have your server configured such that it always returns a 200 status no matter what the URL is because this makes clients or crawlers think there's actually a resource at that URL when there really isn't. A 404 should be returned when you don't have specific content for that URL.