router
Simple middleware-style router
Installation
This is a Node.js module available through the npm registry. Installation is done using the npm install command:
$ npm install routerAPI
var finalhandler = require('finalhandler')
var http = require('http')
var Router = require('router')
var router = Router()
router.get('/', function (req, res) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Hello World!')
})
var server = http.createServer(function (req, res) {
router(req, res, finalhandler(req, res))
})
server.listen(3000)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- Whenfalsetrailing slashes are optional (default:false)caseSensitive- Whentruethe routing will be case sensitive. (default:false)mergeParams- Whentrueanyreq.paramspassed 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
pathis specified, thatpathis stripped from the start ofreq.url.
Middleware can themselves use next('router') at any time to exit the current router instance completely, invoking the top-level callback.
router[method](path, ...[middleware], handler)
The http methods provide the routing functionality in router.
Method middleware and handlers follow usual middleware behavior, except they will only be called when the method and path match the request.
Middleware given before the handler have one additional trick, they may invoke next('route'). Calling next('route') bypasses the remaining middleware and the handler mounted for this route, passing the request to the next route suitable for handling this request.
Route handlers and middleware can themselves use next('router') at any time to exit the current router instance completely, invoking the top-level callback.
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.
The function can optionally return a Promise object. If a Promise object is returned from the function, the router will attach an onRejected callback using .then. If the promise is rejected, next will be called with the rejected value, or an error if the value is falsy.
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.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.
Router.Route(path)
Represents a single route as an instance that 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.
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.
Middleware
Middleware (and method handlers) are functions that follow specific function parameters and have defined behavior when used with router. The most common format is with three parameters - "req", "res" and "next".
req- This is a HTTP incoming message instance.res- This is a HTTP server response instance.next- Calling this function that tellsrouterto proceed to the next matching middleware or method handler. It accepts an error as the first argument.
The function can optionally return a Promise object. If a Promise object is returned from the function, the router will attach an onRejected callback using .then. If the promise is rejected, next will be called with the rejected value, or an error if the value is falsy.
Middleware and method handlers can also be defined with four arguments. When the function has four parameters defined, the first argument is an error and subsequent arguments remain, becoming - "err", "req", "res", "next". These functions are "error handling middleware", and can be used for handling errors that occurred in previous handlers (E.g. from calling next(err)). This is most used when you want to define arbitrary rendering of errors.
Error handling middleware will only be invoked when an error was given. As long as the error is in the pipeline, normal middleware and handlers will be bypassed - only error handling middleware will be invoked with an error.
Examples
You can get the message by running this command in your terminal, or navigating to 127.0.0.1:8080 in a web browser.
You can set the message by sending it a PATCH request via this command:
Example using mergeParams
Now you can get the type, or what path you are requesting:
Example of advanced .route() usage
.route() usageThis example shows how to implement routes where there is a custom handler to execute when the path matched, but no methods matched. Without any special handling, this would be treated as just a generic non-match by router (which typically results in a 404), but with a custom handler, a 405 Method Not Allowed can be sent.
License
Last updated