on-headers
's direct dependencies. Data on all dependencies, including transitive ones, is available via CSV download.Name | Version | Size | License | Type | Vulnerabilities |
---|
The npm package "on-headers" is primarily used to execute a listener when a web server's response is about to write headers. In essence, it allows you to monitor and intervene in the process of setting HTTP headers before they are sent to the client. This can be incredibly useful for adding or modifying headers as per the application's needs, without disrupting the flow of other operations in the server application.
To use "on-headers", you first need to install the package using the npm install command like so:
$ npm install on-headers
Once installed, you require it in your Node.js file with this command:
var onHeaders = require('on-headers')
To add a listener that will execute when headers are emitted for response, you use the onHeaders(res, listener) function where res is the response object and listener is the function to fire. For example:
var http = require('http')
var onHeaders = require('on-headers')
http
.createServer(onRequest)
.listen(3000)
function addPoweredBy () {
// set if not set by end of request
if (!this.getHeader('X-Powered-By')) {
this.setHeader('X-Powered-By', 'Node.js')
}
}
function onRequest (req, res) {
onHeaders(res, addPoweredBy)
res.setHeader('Content-Type', 'text/plain')
res.end('hello!')
}
In the example above, the package triggers the addPoweredBy function just before the headers are written on the response object. If the 'X-Powered-By' header has not been set, it sets it to 'Node.js'.
The official documentation for "on-headers" can be found within the README file on its GitHub repository at https://github.com/jshttp/on-headers
. The documentation provides more details on the API and its usage. Additionally, it provides instructions on how to install the package, test it, and a few examples demonstrating its usage.