A simple vanilla JavaScript router a la ExpressJS.
Code the front-end like the back-end.
Installation
From npm repository
$ npm install frontexpress
From bower repository
$ bower install frontexpress
From CDN
On jsDelivr
Usage
; // Front-end applicationconst app = ; // front-end logic on navigation path "/page1"app; // front-end logic on navigation path "/page2"app; // start front-end applicationapp;
Routes
Listen GET requests on path /hello:
app;
Listen POST requests on path /item:
app;
Listen GET requests on path starting with /api/:
app;
Get parameters from path
app;
app;
app;
You can have the full capabilities of Express-style path with this plugin frontexpress-path-to-regexp
Middleware object
The middleware object gives access to more hooks
= { // before request sent } { // after request sent // res has the request response window; } { // before a new request sent } { // on request failed } { // for chaining return true; } app;
Chain handlers
You can provide multiple handlers functions on a navigation path. Invoking next()
function allows to chain the handlers.
At the opposite, when the next()
method is not called the handler chain is stopped.
const h1 = { console; ; };const h2 = { console };const h3 = { console; ; }; app;app;app;
On navigation on path /example/a, the browser console displays the following:
h1!
h2!
h3 is ignored because next()
function was not invoked.
app.route()
You can create chainable route handlers for a route path by using app.route()
.
app ;
frontexpress.Router
Use the frontexpress.Router
class to create modular, mountable route handlers.
Create a router file named birds.js
:
; const router = frontexpress; // specific middleware for this routerrouter; // listen navigation on the home pagerouter; // listen navigation on the about pagerouter; ;
Then, load the router module in the app:
;...app;
Plugins
Extend frontexpress via plugins:
- frontexpress-path-to-regexp: Add the ability to support Express-style path string such as /user/:name, /user*...
Others are coming
Write your own plugin
It consists to simply create an object with two properties:
- name: the name of your plugin
- plugin: the function containing the implementation
Let's assume that we have implemented this plugin in the frontexpress-my-plugin.js
file as below:
name: 'My plugin' { // the plugin implementation goes here // Some ideas // you can get settings // const transformer = app.get('http GET transformer'); // // you can set settings // app.set('http requester', { // fetch() { // ... // }}); // // you can complete routes // app.get(...) };
To use it:
;; // Front-end applicationconst app = ; // tell to frontexpress to use your pluginapp;
More
Tests
Clone the git repository:
$ git clone git@github.com:camelaissani/frontexpress.git$ cd frontexpress
Install the dependencies and run the test suite:
$ npm install$ npm test