Call nodejs frameworks routes programmatically
All those examples will call GET /some/other/path
when GET /
is called with different frameworks.
# Expressjs 4.x
For example, the endpoint /
transfers the request to another route:
var app = express()
function myRoute(req, res, next) {
return res.send('ok')
}
function home(req, res, next) {
req.url = '/some/other/path'
//if we want to change the method: req.method = 'POST'
return app._router.handle(req, res, next)
}
app.get('/some/other/path', myRoute)
app.get('/', home)
This is not api-documented as it’s a private method, code. It dispatches the req
and res
into the router.
# Hapi.js 11.2
Here it’s almost the same, except that this method is api-documented and can be used for a lot more!
var Hapi = require('hapi')
var server = new Hapi.Server()
server.connection({ port: 3000 })
function myRoute(request, reply) {
return reply('ok')
}
function home(request, reply) {
server.inject({
url: '/some/other/path',
//method: 'POST'
}, function (res) {
return reply(res.result)
})
}
server.route({ method: 'GET', path: '/some/other/path', handler: myRoute })
server.route({ method: 'GET', path: '/', handler: home })
server.start(function() {})
Api is server.inject(options, callback)
and looks really powerful!
# Koa.js 1.1.1 + koa-route 2.4.2
var koa = require('koa')
var route = require('koa-route')
var app = koa()
app.use(route.get('/', home))
app.use(route.get('/some/other/path', myRoute))
function *home(next) {
this.request.url = '/some/other/path'
//this.request.method = 'POST'
yield next
}
function *myRoute() {
this.body = 'ok'
}
app.listen(3000)
Or with 2.0.0-alpaha.2:
var Koa = require('koa')
var route = require('koa-route')
var app = new Koa()
app.use((ctx, next) => {
if(ctx.url == '/') {
ctx.url = '/some/other/path'
}
return next()
})
app.use((ctx, next) => {
ctx.body = 'ok'
})
app.listen(3000)