node-rest-handler
A module for creating a request handler that does REST style routing.
Unlike express, this request handler makes some simplifying assumptions:
- Routes have paths with simple placeholders or static paths (for anything more complicated, a different middleware can be added)
- Instead of passing around
req
,res
, andnext
, these three properties are encapsulated in a single object (therest
object). - Route matching happens before any request handling so that all middleware and final route handler know which route matched. Requests that do not match any routes are a special case and can be handled via a
routeNotFound
listener.
NOTE: The underlying router is https://github.com/philidem/path-based-router/
Installation
npm install rest-handler --save
Usage
Create REST handler:
// Create instance of REST handlervar restHandler = ;
Add some middleware:
// middleware is added via "before" method callrestHandler// Authenticate // Authorize ;
Add some listeners:
// Listen for each request (unlike middleware, listeners are non-sequential)restHandler // Listener for not found ;
Add some routes:
restHandler; // Add a route with parameter placeholderrestHandler;
Route-specific "middleware":
restHandler;
Reading request body:
// Example of reading JSON from request bodyrestHandler; // Example of reading raw text from request bodyrestHandler;
Reading cookies:
// Example of reading raw text from request bodyrestHandler;
Reading basic auth header:
// Echo basic authrestHandler;
Error handling:
// Add a route that will send an errorrestHandler; // Add error handlerrestHandler;
Override notFound handler:
// By default the notFound handler will send the status message as plaintext with a 404 status code.// You can override this behavior using the `onRouteNotFound` option.
Start an http server and delegate handling of requests to REST handler:
// Create standard HTTP servervar server = ; server; server; // Listen on port 8080server;