Methods
By assigning a custom function, we can override the signature and behavior of existing methods. They come into the picture when we discuss overriding the Express API.
Example of overriding the behavior of res.sendStatus.
app.response.sendStatus = function (statusCode, type, message) {
// Simplified code
return this.contentType(type)
.status(statusCode)
.send(message)
}
The above implementation changes the original signature of res.sendStatus entirely. It accepts a message to be sent to the client, status code, and the encoding type.
Now, we can use the overridden method in this way:
res.sendStatus(404, 'application/json', '{"error":"resource not found"}')
Properties
There are two properties in the Express API. They come into the picture when we discuss overriding the Express API. They are:
1. Properties that are assigned(ex: req.baseUrl, req.originalUrl)
The behavior of properties under this category cannot be overridden as their properties are dynamically assigned on the request and response objects in the context of the current request-response cycle.
2. Properties that are defined as getters (ex: req.secure, req.ip)
We can use the Express API extensions API to overwrite the properties under this category.
The following specified below rewrites how the value of req.ip is to be derived. Now, it is simply returning the value of the Client-IP request header.
Object.defineProperty(app.request, 'ip', {
configurable: true,
enumerable: true,
get: function () {
return this.get('Client-IP')
}
})
Frequently Asked Questions
1. What are some of the properties of the Express API?
The properties of the Express API are res.app, res.headersSent, and res.locals.
2. What are some of the methods of the Express API?
There are many methods when we discuss the Express API and overriding the Express API. Some methods of the Express API are req.accepts(types), req.acceptsCharsets(charset [, ...]) and req.get(field), req.range(size[, options]) etc.
3. What is the use of the req.app property?
The req.app property refers to the instance of the Express application that uses the middleware.
Key Takeaways
We have seen that the Express API consists of various methods and properties on the request and response objects. We have looked at overriding the signature and behaviour of existing methods. Hope this article gave you a good idea about overriding the Express API.
If you enjoyed reading this article about overriding the Express API, check out Free JavaScript Tutorial By Coding Ninjas and 10 Best JavaScript Certifications In 2021.