TransWikia.com

Why am i getting the output twice in the Node console?

Stack Overflow Asked by Chetan Batra on December 29, 2020

I have just started learning NodeJS, Kindly help me understand this

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

const app = express();

app.use((req, res, next) => {
    console.log('In the Middleware');
    next();
});
app.use((req, res, next) => {
    console.log('In another Middleware');
    res.send('<h1>Hello From Express</h1>');
});

app.listen(3000);

Output is

In the Middleware
In another Middleware
In the Middleware
In another Middleware

Expected

In the Middleware
In another Middleware

2 Answers

Browsers will often make multiple requests to a server. For example, they will usually try to fetch a favicon.ico file. Another example is a CORS preflight request.

If you open the developer tools in your browser, go to the Network tab, and then refresh your page, you will see all the requests the browser makes (you may need to check the "Disable cache" checkbox first). If you see more than one request, that's probably the reason you're seeing your text logged multiple times.

Another simple way to test this is to try making a request to your server from a client other than your browser. For example, run this from the command line: curl http://localhost:3000. That command should make only a single request to your server. Do you see your text output multiple times in that case? If not, then that's further evidence your browser is making multiple requests to your server.

Answered by Cully on December 29, 2020

I would say that this happens because the browser usually makes a request for the favicon.ico as well, but you can check in the Network tab of the developer tools.

Answered by germanescobar on December 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP