router
Simple middleware-style router
Installation
$ npm install router
API
var finalhandler = var http = var Router = var router = router var server = http server
This module is currently an extracted version from the Express project,
but with the main change being it can be used with a plain http.createServer
object or other web frameworks by removing Express-specific API calls.
Router(options)
Options
strict
- Whenfalse
trailing slashes are optional (default:false
)caseSensitive
- Whentrue
the routing will be case sensitive. (default:false
)mergeParams
- Whentrue
anyreq.params
passed to the router will be merged into the router'sreq.params
. (default:false
) (example)
Returns a function with the signature router(req, res, callback)
where
callback([err])
must be provided to handle errors and fall-through from
not handling requests.
router.use([path], ...middleware)
Use the given middleware function for all http methods on the given path
,
defaulting to the root path.
router
does not automatically see use
as a handler. As such, it will not
consider it one for handling OPTIONS
requests.
- Note: If a
path
is specified, thatpath
is stripped from the start ofreq.url
.
router
router[method](path, ...[middleware], handler)
The http methods provide
the routing functionality in router
.
These are functions which you can directly call on the router to register a new
handler
for the method
at a specified path
.
// handle a `GET` requestrouter
Additional middleware may be given before the handler. These middleware behave
exactly as normal with one exception: they may invoke next('route')
.
Calling next('route')
bypasses the remaining middleware and handler for this
route, passing the request on to the next route.
router.param(name, param_middleware)
Maps the specified path parameter name
to a specialized param-capturing middleware.
This function positions the middleware in the same stack as .use
.
Parameter mapping is used to provide pre-conditions to routes which use normalized placeholders. For example a :user_id parameter could automatically load a user's information from the database without any additional code:
router
router.route(path)
Creates an instance of a single Route
for the given path
.
(See Router.Route
below)
Routes can be used to handle http methods
with their own, optional middleware.
Using router.route(path)
is a recommended approach to avoiding duplicate
route naming and thus typo errors.
var api = router
Router.Route(path)
Represents a single route as an instance that can be used can be used to handle
http methods
with it's own, optional middleware.
route[method](handler)
These are functions which you can directly call on a route to register a new
handler
for the method
on the route.
// handle a `GET` requestvar status = router status
route.all(handler)
Adds a handler for all HTTP methods to this route.
The handler can behave like middleware and call next
to continue processing
rather than responding.
routerall { }allcheck_something
Examples
// import our modulesvar http = var Router = var finalhandler = var compression = var bodyParser = // store our message to displayvar message = "Hello World!" // initialize the router & server and add a final callback.var router = var server = http // use some middleware and compress all outgoing responsesrouter // handle `GET` requests to `/message`router // create and mount a new router for our APIvar api = router // add a body parsing middleware to our APIapi // handle `PATCH` requests to `/api/set-message`api // make our http server listen to connectionsserver
You can get the message by running this command in your terminal,
or navigating to 127.0.0.1:8080
in a web browser.
curl http://127.0.0.1:8080
You can set the message by sending it a PATCH
request via this command:
curl http://127.0.0.1:8080/api/set-message -X PATCH -H "Content-Type: application/json" -d '{"value":"Cats!"}'
Example using mergeParams
var http = var Router = var finalhandler = // this example is about the mergeParams optionvar opts = mergeParams: true // make a router with out special optionsvar router = var server = http router // make another router with our optionsvar handler = // mount our new router to a route that accepts a paramrouter handler // make our http server listen to connectionsserver
Now you can get the type, or what path you are requesting:
curl http://127.0.0.1:8080> kittencurl http://127.0.0.1:8080/such_path> such_path
Implementing Your Own Router
Implementing a custom path matching library on top of this module is as easy as using Router.Engine
. For example, to implement an "exact" path matching module, we can do this:
var Engine = Enginevar slice = Arrayprototypeslice /** * Accepts the path and some options we defined in our engine. */ { if !optionsend return { var matches = path === route return matches ? path: path : false } return { return path === route ? path: path : false }} /** * The constructor must return the engine instance. */ { return Engine} /** * Inherits from the engine prototype. */ExactRouterprototype = Object /** * Set up `Router#use` with our custom path matching implementation. */ExactRouterprototype { // Use a simple utility for supporting a single path argument like `router`. var opts = EnginesanitizeUse var match = return Engineprototypeuse} /** * Set up `Router#route` with our custom path patching implementation. */ExactRouterprototype { var match = return Engineprototyperoute} /** * Set up all the router method shorthands. */Enginemethods
Both the path matching function and the path itself must be passed into the route
and use
engine methods. This is for debugging, so path
should be a human-readable path name. Engine#use
also accepts an array of handlers to immediately include. The match function must return an object of { path: string, params: object }
or false
if it didn't match.
Note: The path matching utility should not throw errors. Decoding of parameters is handled by the engine.