A platform-agnostic router for HTTP listeners that follow the node.js spec
This is a simple and unambitious router implementation that can be used either in the browser, or in any CommonJS environment. It has no dependencies, and weighs in at 462 minizipped bytes. It was designed for browserver, but will work with any server that conforms to the node.js HTTP spec (in which handlers take have a
(req, res) signature, where
method properties, and
Router = require"router"var router ="/salutation/:name":reswriteHead200resend"Hello, " + reqparams0 + "."reswriteHead200resend"Goodbye, " + reqparams0 + "."reswriteHead200resend"Matched method: " + reqmethodvar http = require"http"var server = httpcreateServerrouteronrequestserverlisten8000
var router ="/salutation/:name":reswriteHead200resend"Hello, " + reqparams0 + "."reswriteHead200resend"Goodbye, " + reqparams0 + "."reswriteHead200resend"Matched method: " + reqmethodvar server = httpcreateServerrouteronrequestvar ws = host: "myserver.com"serverlistenws
Creates a new router.
routes is optional, and can be an object where each key is a route pattern, and each value is either a route handler function, or object with methods for keys and route handler functions for values.
Adds a route to match. Both arguments are required. The
route string is compiled into a regular expression, using the same logic as the Backbone.js router, in which
:param strings match a single url component between slashes and
* splats match any number of url components. Any matching parameters are used to populate the
req.params array by match position.
handler function is provided, it will be fired when the route is matched, for any request method.
methodMap object is provided, it will be used to disambiguate between methods of a given route by specifying them as keys, with the handlers for the values.
These properties hold the default handlers. Override them to provide your own fallback logic.