express middleware functions invoked twice when request is made from browser

不羁岁月 提交于 2020-04-03 10:41:45

问题


Below is my nodejs code

const express = require('express');

const app = express();

app.use('/', (req, res, next) => {
    console.log("In interceptor");
    next();
});

app.use('/users', (req, res, next) => {
    console.log('In /users middleware');
    res.send('<h1>From "/users" handler </h1>');
});

app.use('/', (req, res, next) => {
    console.log("Default handler");
    res.send('<h1>From default handler</h1>');
});

app.listen(3000);

Console output when a request is made from browser (both chrome and edge)

http://localhost:3000
******************
In interceptor
Default handler
In interceptor
Default handler
******************

http://localhost:3000/users
******************
In interceptor
In /users middleware
In interceptor
Default handler
******************

But when a request is made using curl, I don't see multiple invocations

curl http://localhost:3000
******************
In interceptor
Default handler
******************

curl http://localhost:3000/users
******************
In interceptor
In /users middleware
******************

Can someone explain why middleware functions are invoked multiple times when request is made from browser?


回答1:


The usual reasons you see multiple requests when a page loads from a browser are one of two things:

  1. The browser automatically requesting the favicon.ico file.
  2. The browser attempting to load some resource from the HTML file (script file, image, CSS file, etc..)

You can see exactly what each request is for by adding:

console.log(req.url);

to your middleware.




回答2:


Found that it is happening due to /favicon.ico request made by browser. Adding specific handler (shown below) prevented default handler from being called twice

app.use('/favicon.ico', (req, res, next) => {
    console.log('favicon handler');
    res.sendStatus(200);
});


来源:https://stackoverflow.com/questions/58045926/express-middleware-functions-invoked-twice-when-request-is-made-from-browser

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!