var app = require(‘express’)(); app.use(function(req,res,next){ console.log(‘请求成功。。。’); next(); }); app.get('/’,function(req,res,next){ console.log(‘有一个错误被抛出。。。’); throw new Error(‘第一个错误’); }); app.use('/’,function(req,res,next){ console.log(‘哈哈哈。。。’); }); app.use('/’,function(error,req,res,next){ console.log(‘检测到错误但不传递’); next(); }); app.use(function(error,req,res,next){ console.log('检测并处理错误。’+error.message); res.send(‘500-服务器出错。’); }); app.use(function(req,res){ console.log(‘未处理错误。’); res.send(‘404-未找到页面。’); }); app.listen(3000,function(){ console.log(‘监听到端口 3000’); });
运行这一段代码,为什么请求成功会执行两次。。 运行结果: 监听到端口 3000 请求成功。。。 有一个错误被抛出。。。 检测到错误但不传递 未处理错误。 请求成功。。。 哈哈哈。。。
@beilunyang
app.use([path,] function [, function...])
Mounts the middleware function(s) at the path. If path is not specified, it defaults to “/”.
Mounting a middleware at a path will cause the middleware function to be executed whenever the base of the requested path matches the path. Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app.
app.METHOD(path, callback [, callback ...])
Routes an HTTP request, where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase.
app.use是middleware, 只要req.path以middleware的模式开始,就会被执行
app.METHOD是route,需要req.path匹配route的模式,才可能被执行
最好自己看文档和例子…