【问题标题】:Nodejs with express : Why my middleware is executing twice Here is the code带有 express 的 Nodejs:为什么我的中间件执行了两次这是代码
【发布时间】:2018-11-30 12:03:20
【问题描述】:

这是我的代码..!

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....');
});

在此我创建了一个名为 myFunc 的中间件,但输出与我想象的不同

Server is running at port 3000....
This is middleware
This is get /
This is middleware

【问题讨论】:

  • console.log(req.url) 添加到中间件。我敢打赌,浏览器要求的是 favicon。
  • 我认为另一个请求是针对 favicon
  • 另一个是favicon!

标签: javascript node.js express middleware


【解决方案1】:

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

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

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

【讨论】:

  • 你说得对。这是因为 favicon.ico 文件。浏览器发送请求两次:1 次用于“/”,1 次用于“/favicon.ico”...非常感谢。
【解决方案2】:

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

【讨论】:

  • 嗯嗯,你确定吗?声明路由或启动服务器都不应该运行中间件或以某种方式重新运行app.use
  • 不,它不起作用我试图删除 app.get 但它也执行了两次!
  • 不,我启动了服务器并重新加载了页面,我在网页上遇到了错误,这是完全可以接受的,但它也执行了两次!
  • @AdityaPradhan 这个答案没有意义。我确信浏览器正在发送另一个请求,要求提供网站图标。您可以通过使用 curl curl http://localhost:3000 发出请求来轻松检查这一点。中间件只会运行一次。
  • 对每个请求都支持 app.getapp.listen 都没有提出请求。
【解决方案3】:

您的静态文件也与您尝试使用的文件共享相同的 url。 所以很可能你会有这样的事情: 本地主机:3000/:变量

这里这个网址会匹配很多东西

【讨论】:

    【解决方案4】:

    正如@DavidWhite 所说,每次触发应用程序时 app.use 都会运行。在这个 如果您触发两次。 app.get 和 app.listen 你应该这样使用中间件

    const express = require('express');
    const app = express();
    
    let myFunc = function (req, res, next) {
        console.log('This is middleware');
        next();
    }
    
    app.get('/', myFunc,(req, res) => {
        console.log('This is get /');
        res.send('Hello World!');
    });
    
    app.listen(3000, () => {
        console.log('Server is running at port 3000....');
    });
    

    【讨论】:

      【解决方案5】:

      当您使用app.use(myFunc); 时,您将中间件应用于所有应用程序。 而您正在使用 app.get 和 app.listen,这就是中间件触发两次的原因。尝试在get查询中使用middlewere

      【讨论】:

      • 我试图删除 app.get 但仍然执行了两次!
      • 是的,这很正常,因为你使用了没有挂载路径的中间件功能。对路由器的每个请求都会执行此代码。不明白为什么它被调用两次,请在中间件中添加 console.log(req.url),就像@Yuri 提到的那样。
      • app.getapp.listen 都不调用他的函数。相反,来自浏览器的每个请求都会调用他的函数。
      猜你喜欢
      • 1970-01-01
      • 2015-05-16
      • 2011-06-16
      • 1970-01-01
      • 2023-02-02
      • 2023-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多