Class based HTTP router
Compatible with Express 4, Hapi or simple HTTP server.
Lightweight, has only debug and path-to-regexp dependencies.
This module is a follow-up to ES6 Class based Express routing blog post.
npm install tilt-router -S
Instead of writing app.get('/', function() {});
or server.router({ method: 'GET', path: '/', handler: function() {}})
to define request handlers, you use
a Class to hold methods registered as route handlers to the underlying
framework, Express or Hapi.
Additionnaly, it implements a simple routing mechanism with raw HTTP server.
import TiltRouter from 'tilt-router'
class Router extends TiltRouter {
get routes() {
'/': 'index'
}
index(req, res) {
console.log('Incoming request:', req.url);
return res.send('Response from server');
}
}
var app = require('express')();
var router = new Router(app);
app.listen(3000);
Or
var app = require('express')();
app.use(Router.middleware(app));
app.listen(3000);
var router = new Router();
router.listen(3000);
Or
var http = require('http');
http.createServer(Router.middleware()).listen(3000);
Or
Router.createServer().listen(3000);
Or
Router.listen(3000);
Router.createServer().
Router.createServer().listen(PORT, done);
Router.listen().
Router.listen(PORT, done);
Router.create().
var router = Router.create();
assert.ok(router instanceof Router);
Router.dispatch() - express middleware.
app.use(Router.middleware(app));
Router.dispatch() - HTTP server.
http.createServer(Router.middleware());
App extends Router.
class App extends Router {
get routes() {
return {
'/': 'index'
};
}
index(req, res, next) {
return res.end('OK');
}
}
var app = new App();
app.listen(PORT, done);
GET /.
request(this.app)
.get('/')
.expect('OK')
.expect(200, done);
var server = TestApp.createServer();
request(this.app)
.get('/aoizheuaziouh')
.expect(404, done);