中间件高效快速大数据排序
A piece of middleware is a function that hooks into the routing process, performing an arbitrary operation at some point in the chain (depending on what we want it to do).
中间件是连接到路由过程的功能,可以在链中的某个点执行任意操作(取决于我们要执行的操作)。
It’s commonly used to edit the request or response objects, or terminate the request before it reaches the route handler code.
通常用于编辑请求或响应对象,或在请求到达路由处理程序代码之前终止请求。
Middleware is added to the execution stack like so:
像这样将中间件添加到执行堆栈中:
app.use((req, res, next) => { /* */ })
This is similar to defining a route, but in addition to the Request and Response objects instances, we also have a reference to the next middleware function, which we assign to the variable next
.
这类似于定义路由,但是除了Request和Response对象实例外,我们还引用了下一个中间件函数,该函数分配给变量next
。
We always call next()
at the end of our middleware function, in order to pass the execution to the next handler. That is unless we want to prematurely end the response and send it back to the client.
我们总是在中间件函数的末尾调用next()
,以便将执行传递给下一个处理程序。 除非我们想过早结束响应并将其发送回客户端。
You typically use pre-made middleware, in the form of npm
packages. A big list of the available ones can be found here.
通常,您使用npm
软件包形式的预制中间件。 可在此处找到大量可用列表。
One example is cookie-parser
, which is used to parse cookies into the req.cookies
object. You can install it using npm install cookie-parser
and you use it thusly:
cookie-parser
是一个示例,它用于将cookie解析为req.cookies
对象。 您可以使用npm install cookie-parser
进行npm install cookie-parser
,因此可以使用它:
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
app.get('/', (req, res) => res.send('Hello World!'))
app.use(cookieParser())
app.listen(3000, () => console.log('Server ready'))
We can also set a middleware function to run for specific routes only (not for all), by using it as the second parameter of the route definition:
通过将其用作路由定义的第二个参数,我们还可以将中间件功能设置为仅针对特定路由(而不是针对所有路由)运行:
const myMiddleware = (req, res, next) => {
/* ... */
next()
}
app.get('/', myMiddleware, (req, res) => res.send('Hello World!'))
If you need to store data that’s generated in a middleware to pass it down to subsequent middleware functions, or to the request handler, you can use the Request.locals
object. It will attach that data to the current request:
如果您需要存储在中间件中生成的数据,以将其传递给后续的中间件功能或请求处理程序,则可以使用Request.locals
对象。 它将数据附加到当前请求:
req.locals.name = 'Flavio'
中间件高效快速大数据排序