Express4中文文档
使用 app.use()
和 app.METHOD()
函数将应用级中间件绑定到 app object 的实例,其中 METHOD
是中间件函数处理的请求的 HTTP 方法(如 GET、PUT 或 POST),小写。
此示例显示了一个没有挂载路径的中间件函数。每次应用收到请求时都会执行该函数。
const express = require('express')
const app = express()
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
})
这个例子展示了一个挂载在 /user/:id
路径上的中间件函数。该函数针对 /user/:id
路径上的任何类型的 HTTP 请求执行。
app.use('/user/:id', (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
这个例子展示了一个路由和它的处理函数(中间件系统)。该函数处理对 /user/:id
路径的 GET 请求。
app.get('/user/:id', (req, res, next) => {
res.send('USER')
})
这是一个在挂载点加载一系列中间件函数的示例,带有挂载路径。它说明了一个中间件子堆栈,它将任何类型的 HTTP 请求的请求信息打印到 /user/:id
路径。
app.use('/user/:id', (req, res, next) => {
console.log('Request URL:', req.originalUrl)
next()
}, (req, res, next) => {
console.log('Request Type:', req.method)
next()
})
路由处理程序使您能够为路径定义多个路由。下面的示例定义了两条到 /user/:id
路径的 GET 请求路由。第二个路由不会引起任何问题,但它永远不会被调用,因为第一个路由结束了请求-响应周期。
此示例显示了一个处理对 /user/:id
路径的 GET 请求的中间件子堆栈。
app.get('/user/:id', (req, res, next) => {
console.log('ID:', req.params.id)
next()
}, (req, res, next) => {
res.send('User Info')
})
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res, next) => {
res.send(req.params.id)
})
要跳过路由器中间件堆栈中的其余中间件功能,请调用 next('route')
将控制权传递给下一个路由。注意:next('route')
仅适用于使用 app.METHOD()
或 router.METHOD()
函数加载的中间件函数。
此示例显示了一个处理对 /user/:id
路径的 GET 请求的中间件子堆栈。
app.get('/user/:id', (req, res, next) => {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route')
// otherwise pass the control to the next middleware function in this stack
else next()
}, (req, res, next) => {
// send a regular response
res.send('regular')
})
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res, next) => {
res.send('special')
})
中间件也可以在数组中声明以实现可重用性。
此示例显示了一个带有中间件子堆栈的数组,用于处理对 /user/:id
路径的 GET 请求
function logOriginalUrl (req, res, next) {
console.log('Request URL:', req.originalUrl)
next()
}
function logMethod (req, res, next) {
console.log('Request Type:', req.method)
next()
}
const logStuff = [logOriginalUrl, logMethod]
app.get('/user/:id', logStuff, (req, res, next) => {
res.send('User Info')
})