The Express API consists of various methods and properties on the request and response objects. expressapi由请求和响应对象上的各种方法和属性组成。These are inherited by prototype. There are two extension points for the Express API:这些都是由原型继承的。Express API有两个扩展点:
express.request
and express.response
.express.request
和express.response
处的全局原型。app.request
and app.response
.app.request
和app.response
上的特定于应用程序的原型。Altering the global prototypes will affect all loaded Express apps in the same process. 更改全球原型将影响同一过程中加载的所有Express应用程序。If desired, alterations can be made app-specific by only altering the app-specific prototypes after creating a new app.如果需要,在创建新的应用程序后,只需更改特定于应用程序的原型,就可以进行特定于应用程序的更改。
You can override the signature and behavior of existing methods with your own, by assigning a custom function.通过指定自定义函数,可以用自己的方法覆盖现有方法的签名和行为。
Following is an example of overriding the behavior of res.sendStatus.下面是重写res.sendStatus
行为的示例。
app.response.sendStatus = function (statusCode, type, message) {
// 出于演示目的,代码有意保持简单
return this.contentType(type)
.status(statusCode)
.send(message)
}
The above implementation completely changes the original signature of 上述实现完全改变了res.sendStatus
. res.sendStatus
的原始签名。It now accepts a status code, encoding type, and the message to be sent to the client.它现在接受状态代码、编码类型和要发送到客户端的消息。
The overridden method may now be used this way:现在可以这样使用重写的方法:
res.sendStatus(404, 'application/json', '{"error":"resource not found"}')
Properties in the Express API are either:Express API中的属性为:
req.baseUrl
, req.originalUrl
)req.baseUrl
、req.originalUrl
)req.secure
, req.ip
)req.secure
、req.ip
)Since properties under category 1 are dynamically assigned on the 由于类别1下的属性是在当前请求-响应周期的上下文中动态分配给request
and response
objects in the context of the current request-response cycle, their behavior cannot be overridden.request
和response
对象的,因此无法覆盖它们的行为。
Properties under category 2 can be overwritten using the Express API extensions API.可以使用Express API extensions API覆盖类别2下的属性。
The following code rewrites how the value of 下面的代码重写了req.ip
is to be derived. req.ip
值的推导方式。Now, it simply returns the value of the 现在,它只返回Client-IP
request header.Client-IP
请求头的值。
Object.defineProperty(app.request, 'ip', {
configurable: true,
enumerable: true,
get: function () { return this.get('Client-IP') }
})