on-request — take over the request
handler of a Node HTTP server.
How to use
import http from 'http';
import onRequest from 'on-request';
const srv = http.createServer((req, res) => {
res.end('Handling', req.url);
});
onRequest(srv, (req, res, next) => {
if ('/special' === req.url) {
res.end('Special request!');
} else {
next();
}
});
API
onRequest()
onRequest(srv : http.Server, fn : Function, onError : fn)
- Exported as
default
. Useimport onRequest from 'on-request'
(ES6) orrequire('on-request').default
(legacy). -
onError
is executed whennext
is invoked but no other request handlers are present. By default it returns501 Unimplemented
to prevent requests from hanging and allocating resources. It's invoked with the following parameters:- The
http.IncomingRequest
- The
http.OutgoingResponse
- The
- The supplied
fn
function receives three parameters:- The
http.IncomingRequest
- The
http.OutgoingResponse
- A function callback that invokes the rest of the request handlers
- The
Caveats
- Beware that
request
listeners registered afteronRequest
will be fired simultaneously. - After using
onRequest
all the existing listeners will be "removed' and no longer exposed to.listeners()
.
Credits
- Copyright © 2016 Zeit, Inc and project authors.
- Licensed under MIT.
- ▲