express-route is a library that let you organize the routes for express applications.
express-route is a library that let you organize the routes for the express applications.
- single method API to read and apply the routes
- ability to read routes synchronously or asynchronously
- versatile format of the route definition to support all cases
Firstly, you need to define the routes. The route can be a function, an object or an array of objects. They can be in one file or in many files.
The simplest definition may look like this:
This definition is simply translated to the following code:
get is a default HTTP method. You can change it using an object definition:
moduleexports ='/home':methods: 'post'resend'Hello!';;
To apply the routes to the express application you need to call
route with valid parameters:
var route = require'express-route';// app is a reference to the express application// './routes' is a path to the directory with the routes// the third parameter is a configuration objectrouteapp './routes'// retrieve routes synchronouslysync: true// action to invoke when route is marked as restricted: trueif !userauthorizedresstatus403end'Forbidden';return;next;;
The definition of the route may be slightly more complicated:
'use strict';moduleexports =// route with restricted setting on'/user':resend'user';restricted: true// route that accepts several methods'/user/categories':resend'method ' + reqmethod + ' post #' + reqparamsid;methods: 'get' 'post'// several actions with different HTTP methods for one route'/user/posts/:id':resend'method ' + reqmethod + ' post #' + reqparamsid;restricted: truemethods: 'get' 'delete'resend'method ' + reqmethod + ' post #' + reqparamsid;restricted: truemethods: 'post';
Apply routes to the express application.
app- reference to the express application,
path- path to the folder or the file with the routes,
settings- a configuration object,
sync: Boolean- whether the load of the routings is synchronous or not (optional,
ensureRestriction: Function- middleware which check if the request is authenticated (optional, by default it's a function that accepts all requests),
ext: Array- array with valid file extensions, e.g.