on-request

1.0.0 • Public • Published

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. Use import onRequest from 'on-request' (ES6) or require('on-request').default (legacy).
  • onError is executed when next is invoked but no other request handlers are present. By default it returns 501 Unimplemented to prevent requests from hanging and allocating resources. It's invoked with the following parameters:
    • The http.IncomingRequest
    • The http.OutgoingResponse
  • The supplied fn function receives three parameters:
    • The http.IncomingRequest
    • The http.OutgoingResponse
    • A function callback that invokes the rest of the request handlers

Caveats

  • Beware that request listeners registered after onRequest 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.

Readme

Keywords

none

Package Sidebar

Install

npm i on-request

Weekly Downloads

20

Version

1.0.0

License

none

Last publish

Collaborators

  • rauchg