node.js - Express中间件奇怪的执行结果

标签 node.js express

我的代码:

var http = require("http");
var express = require("express");
var app = express();

app.set('port',3332);

app.get('/',function(req,res,next){
    res.send('OK');
    next();
});

app.use(function(req,res,next){
    console.log('middleware 1');
    next();
});

app.use(function(req,res,next){
    console.log('middleware 2');
});

http.createServer(app).listen(app.set('port'),function(){
    console.log('nodejs start listen 3332 port!');
});

nodejs服务器输出: Nodejs开始监听3332端口!

中间件1

中间件2

中间件1

中间件2

为什么每个中间件都会被触发两次,有人可以帮我解释一下吗?我知道如果在 app.get() 中删除 next() ,它将被触发 1 次。中间件的链是圆链吗?谢谢。

修改代码,在最后一个app.use()中添加next()。还有一个问题:

var http = require("http");

var express = require("express");
var app = express();

app.set('port',3332);

app.get('/',function(req,res,next){
    res.send('OK');
    next();
});

app.use(function(req,res,next){
    console.log('middleware 1');
    next();
});

app.use(function(req,res,next){
    console.log('middleware 2');
    next(); // new add
});

http.createServer(app).listen(app.set('port'),function(){
    console.log('nodejs start listen 3332 port!');
});

当我第一次访问该网址时,会调用 app.use() 注册的中间件。但是第二次、第三次在浏览器和cmd命令行中访问该url,则不会被调用。 为什么会这样?

最佳答案

这是favicon.ico请求。每次您请求网站索引页面时,浏览器都会尝试加载网站图标。输出 url 以在控制台中查看它。使用curl/wget来运行请求。

关于node.js - Express中间件奇怪的执行结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38142357/

相关文章:

json - 无法升级到 Angular4

mysql - NodeJS - 处理 100 多个并发连接的内存不足

node.js - 部署 Node.js Web 应用程序时最重要的统计数据是什么?

javascript - 使用 NodeJS 更新图像

javascript - 我是否应该考虑在应用程序引导期间阻塞 I/O 的不良做法? ( Node .js)

node.js - 理解 Node.js 中的 try 和 catch

node.js - Express 服务的 Vuejs 前端和 Node 安全实践中的后端 API

node.js - 在多个 NPM 包之间共享一个 Mongoose 实例

javascript - 如何读取本地pdf文件并将其作为expressJS应用程序的响应发送?

javascript - 在下拉菜单中设置选定值