注:我很新表达
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
var things = require('./things/things.js');
//both index.js and things.js should be in same directory
app.use('/things', things);
//Simple request time logger
app.use('/',function(req, res, next){
console.log("A new request received at " + Date.now());
//This function call is very important. It tells that more processing is
//required for the current request and is in the next middleware
//function/route handler.
next();
});
app.listen(3000);
我正在学习中间件功能,并尝试在访问 localhost:3000 时显示 console.log 消息,但控制台中没有显示任何内容,我在这里缺少什么?
问题在于 Express 将请求按照声明的顺序传递给中间件和路由处理程序。如果它们中的任何一个能够处理请求(通过发回响应),则稍后声明的任何其他匹配的中间件或路由处理程序都不会被调用。
这就是您的情况所发生的情况,您的中间件被声明after路线处理程序。
尝试将中间件移到前面:
app.use('/',function(req, res, next){
console.log("A new request received at " + Date.now());
next();
});
app.get('/', function(req, res) {
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
var things = require('./things/things.js');
app.use('/things', things);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)