为什么中间件的内容在浏览器的单个请求中运行四次

时间:2018-11-11 11:36:25

标签: node.js express mean-stack meanjs

console.log('First Log')为什么每个请求运行4次?

//app.js
const express = require('express');
var app = express();

app.use((req, res, next) => {
  console.log('First Log'); // problem is here
  next();
});

app.use((req, res, next) => {
  res.send('first response from express');
});

module.exports = app;
//server.js
const http = require('http');
const app  = require('./backend/app');

var port =  process.env.PORT || 3000;

app.set('port', port);

var server = http.createServer(app);
server.listen(port);

输出:

First Log
First Log
First Log
First Log

1 个答案:

答案 0 :(得分:1)

中间件可以是所有路径通用的,也可以仅在服务器处理的特定路径上触发。以下是中间件声明的示例。

var app = express();
app.use(function () {}) //added to all paths or globally
app.get('/someroute', function() {}) //added to a specific path

参考https://medium.com/@agoiabeladeyemi/a-simple-explanation-of-express-middleware-c68ea839f498

@AikonMogwai在评论中提到的答案也是正确的:

The middleware works one time for each url(of the same route path): index.html, favicon.ico, *.css, etc. 
Change console.log to console.log(req.url) to see that.