打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Express模块 app.use() Specification
app.use([path,] callback [, callback...])
Mounts the specified middleware function or functions at the specified path: the middleware function is executed when the base of the requested path matches path.
Arguments
ArgumentDescriptionDefault
pathThe path for which the middleware function is invoked; can be any of:
A string representing a path.
A path pattern.
A regular expression pattern to match paths.
An array of combinations of any of the above.
For examples, see Path examples.'/' (root path)
callbackCallback functions; can be:
A middleware function.
A series of middleware functions (separated by commas).
An array of middleware functions.
A combination of all of the above.
You can provide multiple callback functions that behave just like middleware, except that these callbacks can invoke next('route') to bypass the remaining route callback(s). You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there is no reason to proceed with the current route.
Since router and app implement the middleware interface, you can use them as you would any other middleware function.
For examples, see Middleware callback function examples.
None
Description
A route will match any path that follows its path immediately with a “/”. For example: app.use('/apple', ...) will match “/apple”, “/apple/images”, “/apple/images/news”, and so on.
Since path defaults to “/”, middleware mounted without a path will be executed for every request to the app.
For example, this middleware function will be executed for every request to the app:
app.use(function (req, res, next) { console.log('Time: %d', Date.now()) next()})NOTE
Sub-apps will:
Not inherit the value of settings that have a default value. You must set the value in the sub-app.
Inherit the value of settings with no default value.
For details, see Application settings.
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.
// this middleware will not allow the request to go beyond itapp.use(function (req, res, next) { res.send('Hello World')})// requests will never reach this routeapp.get('/', function (req, res) { res.send('Welcome')})Error-handling middleware
Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors. For details about error-handling middleware, see: Error handling.
Define error-handling middleware functions in the same way as other middleware functions, except with four arguments instead of three, specifically with the signature (err, req, res, next)):
app.use(function (err, req, res, next) { console.error(err.stack) res.status(500).send('Something broke!')})Path examples
The following table provides some simple examples of valid path values for mounting middleware.
TypeExample
PathThis will match paths starting with `/abcd`:app.use('/abcd', function (req, res, next) { next();});
Path PatternThis will match paths starting with `/abcd` and `/abd`:app.use('/abc?d', function (req, res, next) { next();});This will match paths starting with `/abcd`, `/abbcd`, `/abbbbbcd`, and so on:app.use('/ab+cd', function (req, res, next) { next();});This will match paths starting with `/abcd`, `/abxcd`, `/abFOOcd`, `/abbArcd`, and so on:app.use('/ab\*cd', function (req, res, next) { next();});This will match paths starting with `/ad` and `/abcd`:app.use('/a(bc)?d', function (req, res, next) { next();});
Regular ExpressionThis will match paths starting with `/abc` and `/xyz`:app.use(/\/abc|\/xyz/, function (req, res, next) { next();});
ArrayThis will match paths starting with `/abcd`, `/xyza`, `/lmn`, and `/pqr`:app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { next();});
Middleware callback function examples
The following table provides some simple examples of middleware functions that can be used as the callback argument to app.use(), app.METHOD(), and app.all(). Even though the examples are for app.use(), they are also valid for app.use(), app.METHOD(), and app.all().
UsageExample
Single MiddlewareYou can define and mount a middleware function locally.app.use(function (req, res, next) { next();});A router is valid middleware.var router = express.Router();router.get('/', function (req, res, next) { next();});app.use(router);An Express app is valid middleware.var subApp = express();subApp.get('/', function (req, res, next) { next();});app.use(subApp);
Series of MiddlewareYou can specify more than one middleware function at the same mount path.var r1 = express.Router();r1.get('/', function (req, res, next) { next();});var r2 = express.Router();r2.get('/', function (req, res, next) { next();});app.use(r1, r2);
ArrayUse an array to group middleware logically. If you pass an array of middleware as the first or only middleware parameters, then you must specify the mount path.var r1 = express.Router();r1.get('/', function (req, res, next) { next();});var r2 = express.Router();r2.get('/', function (req, res, next) { next();});app.use('/', [r1, r2]);
CombinationYou can combine all the above ways of mounting middleware.function mw1(req, res, next) { next(); }function mw2(req, res, next) { next(); }var r1 = express.Router();r1.get('/', function (req, res, next) { next(); });var r2 = express.Router();r2.get('/', function (req, res, next) { next(); });var subApp = express();subApp.get('/', function (req, res, next) { next(); });app.use(mw1, [mw2, r1, r2], subApp);
Following are some examples of using the express.static middleware in an Express app.
Serve static content for the app from the “public” directory in the application directory:
// GET /style.css etcapp.use(express.static(path.join(__dirname, 'public')))Mount the middleware at “/static” to serve static content only when their request path is prefixed with “/static”:
// GET /static/style.css etc.app.use('/static', express.static(path.join(__dirname, 'public')))Disable logging for static content requests by loading the logger middleware after the static middleware:
app.use(express.static(path.join(__dirname, 'public')))app.use(logger())Serve static files from multiple directories, but give precedence to “./public” over the others:
app.use(express.static(path.join(__dirname, 'public')))app.use(express.static(path.join(__dirname, 'files')))app.use(express.static(path.join(__dirname, 'uploads')))
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
express中间件
Express 工具库中的 Application 对象
【实践篇】node实现mock小工具
Node.js 学习笔记:使用 Express 框架
Express 4.0 升级手记【站长博客网】
Node.js Express WEB框架
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服