Gathering detailed insights and metrics for router
Gathering detailed insights and metrics for router
Gathering detailed insights and metrics for router
Gathering detailed insights and metrics for router
npm install router
Module System
Unable to determine the module system for this package.
Min. Node Version
Typescript Support
Node Version
NPM Version
410 Stars
383 Commits
104 Forks
20 Watching
10 Branches
33 Contributors
Updated on 12 Nov 2024
JavaScript (100%)
Cumulative downloads
Total Downloads
Last day
-0.3%
170,670
Compared to previous day
Last week
3.6%
947,576
Compared to previous week
Last month
18.2%
3,822,496
Compared to previous month
Last year
13.3%
33,249,208
Compared to previous year
Simple middleware-style router
This is a Node.js module available through the
npm registry. Installation is done using the
npm install
command:
1$ npm install router
1var finalhandler = require('finalhandler') 2var http = require('http') 3var Router = require('router') 4 5var router = Router() 6router.get('/', function (req, res) { 7 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 8 res.end('Hello World!') 9}) 10 11var server = http.createServer(function (req, res) { 12 router(req, res, finalhandler(req, res)) 13}) 14 15server.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.
Options
strict
- When false
trailing slashes are optional (default: false
)caseSensitive
- When true
the routing will be case sensitive. (default: false
)mergeParams
- When true
any req.params
passed to the router will be
merged into the router's req.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.
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.
path
is specified, that path
is stripped from the start of
req.url
.1router.use(function (req, res, next) { 2 // do your things 3 4 // continue to the next middleware 5 // the request will stall if this is not called 6 next() 7 8 // note: you should NOT call `next` if you have begun writing to the response 9})
Middleware can themselves use next('router')
at any time to
exit the current router instance completely, invoking the top-level callback.
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.
1// handle a `GET` request 2router.get('/', function (req, res) { 3 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 4 res.end('Hello World!') 5})
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.
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:
1router.param('user_id', function (req, res, next, id) { 2 User.find(id, function (err, user) { 3 if (err) { 4 return next(err) 5 } else if (!user) { 6 return next(new Error('failed to load user')) 7 } 8 req.user = user 9 10 // continue processing the request 11 next() 12 }) 13})
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.
1var api = router.route('/api/')
Represents a single route as an instance that can be used to handle http
methods
with it's own, optional middleware.
These are functions which you can directly call on a route to register a new
handler
for the method
on the route.
1// handle a `GET` request 2var status = router.route('/status') 3 4status.get(function (req, res) { 5 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 6 res.end('All Systems Green!') 7})
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.
1router.route('/') 2 .all(function (req, res, next) { 3 next() 4 }) 5 .all(checkSomething) 6 .get(function (req, res) { 7 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 8 res.end('Hello World!') 9 })
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 tells router
to 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.
1router.get('/error_route', function (req, res, next) { 2 return next(new Error('Bad Request')) 3}) 4 5router.use(function (err, req, res, next) { 6 res.end(err.message) //= > "Bad Request" 7})
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.
1// import our modules 2var http = require('http') 3var Router = require('router') 4var finalhandler = require('finalhandler') 5var compression = require('compression') 6var bodyParser = require('body-parser') 7 8// store our message to display 9var message = 'Hello World!' 10 11// initialize the router & server and add a final callback. 12var router = Router() 13var server = http.createServer(function onRequest (req, res) { 14 router(req, res, finalhandler(req, res)) 15}) 16 17// use some middleware and compress all outgoing responses 18router.use(compression()) 19 20// handle `GET` requests to `/message` 21router.get('/message', function (req, res) { 22 res.statusCode = 200 23 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 24 res.end(message + '\n') 25}) 26 27// create and mount a new router for our API 28var api = Router() 29router.use('/api/', api) 30 31// add a body parsing middleware to our API 32api.use(bodyParser.json()) 33 34// handle `PATCH` requests to `/api/set-message` 35api.patch('/set-message', function (req, res) { 36 if (req.body.value) { 37 message = req.body.value 38 39 res.statusCode = 200 40 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 41 res.end(message + '\n') 42 } else { 43 res.statusCode = 400 44 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 45 res.end('Invalid API Syntax\n') 46 } 47}) 48 49// make our http server listen to connections 50server.listen(8080)
You can get the message by running this command in your terminal,
or navigating to 127.0.0.1:8080
in a web browser.
1curl http://127.0.0.1:8080
You can set the message by sending it a PATCH
request via this command:
1curl http://127.0.0.1:8080/api/set-message -X PATCH -H "Content-Type: application/json" -d '{"value":"Cats!"}'
1var http = require('http') 2var Router = require('router') 3var finalhandler = require('finalhandler') 4 5// this example is about the mergeParams option 6var opts = { mergeParams: true } 7 8// make a router with out special options 9var router = Router(opts) 10var server = http.createServer(function onRequest (req, res) { 11 // set something to be passed into the router 12 req.params = { type: 'kitten' } 13 14 router(req, res, finalhandler(req, res)) 15}) 16 17router.get('/', function (req, res) { 18 res.statusCode = 200 19 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 20 21 // with respond with the the params that were passed in 22 res.end(req.params.type + '\n') 23}) 24 25// make another router with our options 26var handler = Router(opts) 27 28// mount our new router to a route that accepts a param 29router.use('/:path', handler) 30 31handler.get('/', function (req, res) { 32 res.statusCode = 200 33 res.setHeader('Content-Type', 'text/plain; charset=utf-8') 34 35 // will respond with the param of the router's parent route 36 res.end(req.params.path + '\n') 37}) 38 39// make our http server listen to connections 40server.listen(8080)
Now you can get the type, or what path you are requesting:
1curl http://127.0.0.1:8080 2> kitten 3curl http://127.0.0.1:8080/such_path 4> such_path
.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.
1var http = require('http') 2var finalhandler = require('finalhandler') 3var Router = require('router') 4 5// create the router and server 6var router = new Router() 7var server = http.createServer(function onRequest (req, res) { 8 router(req, res, finalhandler(req, res)) 9}) 10 11// register a route and add all methods 12router.route('/pet/:id') 13 .get(function (req, res) { 14 // this is GET /pet/:id 15 res.setHeader('Content-Type', 'application/json') 16 res.end(JSON.stringify({ name: 'tobi' })) 17 }) 18 .delete(function (req, res) { 19 // this is DELETE /pet/:id 20 res.end() 21 }) 22 .all(function (req, res) { 23 // this is called for all other methods not 24 // defined above for /pet/:id 25 res.statusCode = 405 26 res.end() 27 }) 28 29// make our http server listen to connections 30server.listen(8080)
No vulnerabilities found.
Reason
15 commit(s) and 4 issue activity found in the last 90 days -- score normalized to 10
Reason
security policy file detected
Details
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
GitHub workflow tokens follow principle of least privilege
Details
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
Found 12/15 approved changesets -- score normalized to 8
Reason
dependency not pinned by hash detected -- score normalized to 3
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More