- 快速入门
- 指南
- 参考手册
- 高级主题
- 资源
- Express 词汇表
- Express 社区
- 模板引擎
- Express 中间件
- Express body-parser middleware
- Express compression middleware
- Express connect-rid middleware
- Express cookie-parser middleware
- Express cookie-session middleware
- Express cors middleware
- Express csurf middleware
- Express errorhandler middleware
- Express method-override middleware
- Express morgan middleware
- Express multer middleware
- Express response-time middleware
- Express serve-favicon middleware
- Express serve-index middleware
- Express serve-static middleware
- Express session middleware
- Express timeout middleware
- Express vhost middleware
- Express 实用模板
- 推荐框架
- 推荐书籍和博客
开发中间件
Overview
Middleware functions are functions that have access to the request object (req
), the response object (res
), and the next
function in the application’s request-response cycle. The next
function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can perform the following tasks:
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware in the stack.
If the current middleware function does not end the request-response cycle, it must call next()
to pass control to the next middleware function. Otherwise, the request will be left hanging.
The following figure shows the elements of a middleware function call:
HTTP method for which the middleware function applies. Path (route) for which the middleware function applies. The middleware function. Callback argument to the middleware function, called "next" by convention. HTTP response argument to the middleware function, called "res" by convention. HTTP request argument to the middleware function, called "req" by convention. |
Example
Here is an example of a simple “Hello World” Express application. The remainder of this article will define and add two middleware functions to the application: one called myLogger
that prints a simple log message and another called requestTime
that displays the timestamp of the HTTP request.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Middleware function myLogger
Here is a simple example of a middleware function called “myLogger”. This function just prints “LOGGED” when a request to the app passes through it. The middleware function is assigned to a variable named myLogger
.
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
Notice the call above to next()
. Calling this function invokes the next middleware function in the app. The next()
function is not a part of the Node.js or Express API, but is the third argument that is passed to the middleware function. The next()
function could be named anything, but by convention it is always named “next”. To avoid confusion, always use this convention.
To load the middleware function, call app.use()
, specifying the middleware function. For example, the following code loads the myLogger
middleware function before the route to the root path (/).
var express = require('express')
var app = express()
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
Every time the app receives a request, it prints the message “LOGGED” to the terminal.
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
If myLogger
is loaded after the route to the root path, the request never reaches it and the app doesn’t print “LOGGED”, because the route handler of the root path terminates the request-response cycle.
The middleware function myLogger
simply prints a message, then passes on the request to the next middleware function in the stack by calling the next()
function.
Middleware function requestTime
Next, we’ll create a middleware function called “requestTime” and add a property called requestTime
to the request object.
var requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
The app now uses the requestTime
middleware function. Also, the callback function of the root path route uses the property that the middleware function adds to req
(the request object).
var express = require('express')
var app = express()
var requestTime = function (req, res, next) {
req.requestTime = Date.now()
next()
}
app.use(requestTime)
app.get('/', function (req, res) {
var responseText = 'Hello World!<br>'
responseText += '<small>Requested at: ' + req.requestTime + '</small>'
res.send(responseText)
})
app.listen(3000)
When you make a request to the root of the app, the app now displays the timestamp of your request in the browser.
Because you have access to the request object, the response object, the next middleware function in the stack, and the whole Node.js API, the possibilities with middleware functions are endless.
For more information about Express middleware, see: Using Express middleware.
Configurable middleware
If you need your middleware to be configurable, export a function which accepts an options object or other parameters, which, then returns the middleware implementation based on the input parameters.
File: my-middleware.js
module.exports = function (options) {
return function (req, res, next) {
// Implement the middleware function based on the options object
next()
}
}
The middleware can now be used as shown below.
var mw = require('./my-middleware.js')
app.use(mw({ option1: '1', option2: '2' }))
Refer to cookie-session and compression for examples of configurable middleware.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论