Nodejs with express:为什么我的中间件执行两次这里是代码

Adi*_*han 3 javascript middleware node.js express

这是我的代码在这里..!

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

let myFunc = function (req, res, next) {
    console.log('This is middleware');
    next();
}

app.use(myFunc);

app.get('/', (req, res) => {
    console.log('This is get /');
    res.send('Hello World!');
});

app.listen(3000, () => {
    console.log('Server is running at port 3000....');
});
Run Code Online (Sandbox Code Playgroud)

在此,我创建了一个名为 myFunc 的中间件,但输出并不像我想象的那样

Server is running at port 3000....
This is middleware
This is get /
This is middleware
Run Code Online (Sandbox Code Playgroud)

Int*_*lia 9

发生这种情况是因为浏览器正在请求两个文件。第一个将用于/,第二个可能用于favicon.ico。如果您想了解为什么要调用它,请将您的一个函数更改为如下所示:

let myFunc = function (req, res, next) {
  console.log('This is middleware', req.originalUrl);
  next();
}
Run Code Online (Sandbox Code Playgroud)

然后它会输出每次浏览器访问服务器时请求的 URL。


Dav*_*ite 3

每次触发应用程序时,app.use 都会运行。在这种情况下,您会触发两次。app.get 和 app.listen

  • @AdityaPradhan 这个答案毫无意义。我确信浏览器正在发送另一个请求,要求提供网站图标。您可以通过使用curl `curl http://localhost:3000` 发出请求来轻松检查这一点。中间件只会运行一次。 (3认同)