【问题标题】:ExpressJs is console logging two timesExpressJs 是控制台记录两次
【发布时间】:2021-03-08 05:54:55
【问题描述】:

当我只创建一个服务器并在浏览器中加载一次时,我不明白为什么我的代码会记录两次消息。

输入 -

const express = require('express');

const app = express();

app.use((req, res, next) => {
    console.log('Hello middleware')
    next(); // Allows the request to continue to the next middleware in line
});

app.use((req, res, next) => {
    console.log('Hello middleware v2')
    res.send('<h1>Hello Express!</h1>');
});

app.listen(3000);

输出 -

[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
Hello middleware
Hello middleware v2
Hello middleware
Hello middleware v2

package.json -

{
  "name": "nodeproject1",
  "version": "1.0.0",
  "description": "node tutorial",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "Arkapratim Sarkar",
  "license": "ISC",
  "devDependencies": {
    "nodemon": "^2.0.6"
  },
  "dependencies": {
    "express": "^4.17.1"
  }
}

【问题讨论】:

  • 如何调用请求?在console.log 中添加更多调试信息,例如源端口和 ip。所以你可以看看是多个请求还是有其他问题
  • 正如我提到的 'app.listen(3000);'并转到“本地主机:3000”。无论如何@eol指出默认图标文件也在发出请求,因此双重日志记录

标签: node.js express nodemon


【解决方案1】:

如果您通过浏览器执行请求,则不仅会针对相应的请求路径(例如/)发送请求,还会针对/favicon.ico 发送请求(详细说明here)。 由于发出了两个请求,因此您会看到每个中间件的日志消息两次。

【讨论】:

  • 感谢您的解释。我一直在开发工具的网络选项卡中看到这个“/favicon.ico”,但不认为它也在发出不同的请求。
猜你喜欢
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
相关资源
最近更新 更多