编写中间件以用于 Express 应用程序
概述
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.
中间件函数可以执行以下任务:
- 执行任何代码。
- 对请求和响应对象进行更改。
- 结束请求/响应循环。
- 调用堆栈中的下一个中间件。
如果当前中间件函数没有结束请求/响应循环,那么它必须调用 next(),以将控制权传递给下一个中间件函数。否则,请求将保持挂起状态。 Otherwise, the request will be left hanging.
以下示例显示中间件函数调用的元素:
|
中间件函数适用的 HTTP 方法。 </tbody>
中间件函数适用的路径(路由)。
中间件函数。
中间件函数的回调自变量,按约定称为“next”。
HTTP response argument to the middleware function, called "res" by convention.
HTTP request argument to the middleware function, called "req" by convention.
|