![](/img/trans.png)
[英]express middleware functions invoked twice when request is made from browser
[英]Why content of middleware is running four times on single request from browser
為什么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
中間件可以是所有路徑通用的,也可以僅在服務器處理的特定路徑上觸發。 以下是中間件聲明的示例。
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.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.