var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8000, function () {
console.log('Hello World is listening at port 8000');
});
// invoked for any requests passed to this router
router.use(function(req, res, next) {
// .. some logic here .. like any other middleware
next();
});
// will handle any request that ends in /events
// depends on where the router is "use()'d"
router.get('/events', function(req, res, next) {
// ..
});
An Express application is essentially a stack of middleware which are executed serially.(express应用其实就是由一系列顺序执行的Middleware组成。)
A middleware is a function with access to the request object (req), the response object (res), and the next middleware in line in the request-response cycle of an Express application. It is commonly denoted by a variable named next. Each middleware has the capacity to execute any code, make changes to the request and the reponse object, end the request-response cycle, and call the next middleware in the stack. Since middleware are execute serially, their order of inclusion is important.(中间件其实就是一个访问express应用串入的req,res,nex参数的函数,这个函数可以访问任何通过req,res传入的资源。)
If the current middleware is not ending the request-response cycle, it is important to call next() to pass on the control to the next middleware, else the request will be left hanging.(如果当前中间件没有完成对网页的res响应 ,还可以通过next把router 留给下一个middleware继续执行)
With an optional mount path, middleware can be loaded at the application level or at the router level. Also, a series of middleware functions can be loaded together, creating a sub-stack of middleware system at a mount point.
var express = require('express');
var app = express();
var router = express.Router();
app.get('/', function(req, res){
console.log('test1');
});
app.use('/', function(req, res){
console.log('test2');
});
router.get('/', function(req, res){
console.log('test3');
});
app.listen(4000);
输入url: localhost:4000
输出结果:test1
输入url: localhost:4000/hello
输出结果:test2
结论:app.get挂载‘/’的路由只响应跟'/'精确匹配的GET请求。 而app.use挂载的'/'的路由响应所有以'/' 为起始路由的路由,且不限制HTTP访问的方法。以下说明:Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.
1 app.use([path], [function...], function)
2 Mount the middleware function(s) at the path. If path is not specified, it defaults to "/".
3
4 Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path.