最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there a Express-style nested router for Koa.js? - Stack Overflow

programmeradmin5浏览0评论

Is there exist a library that provides Express-style nesting routers? Something like this:

var koa = require('koa');
var app = koa();
var Router = require('???');

var restApiRouter = Router();
restApiRouter.get('/', function*() {
  // respond to /api/
});
restApiRouter.get('/messages', function*() {
  // respond to /api/messages
});

var appRouter = new Router();
appRouter.get('/', function*() {
  // respond to /
});
// redirects all /api/* requests to restApiRouter
appRouter.use('/api', restApiRouter);

app.use(appRouter);

If there isn't, what is the best practice to incapsulate mon path routes in other files?

Is there exist a library that provides Express-style nesting routers? Something like this:

var koa = require('koa');
var app = koa();
var Router = require('???');

var restApiRouter = Router();
restApiRouter.get('/', function*() {
  // respond to /api/
});
restApiRouter.get('/messages', function*() {
  // respond to /api/messages
});

var appRouter = new Router();
appRouter.get('/', function*() {
  // respond to /
});
// redirects all /api/* requests to restApiRouter
appRouter.use('/api', restApiRouter);

app.use(appRouter);

If there isn't, what is the best practice to incapsulate mon path routes in other files?

Share Improve this question edited Jun 28, 2017 at 7:39 laser 1,37613 silver badges14 bronze badges asked Apr 15, 2015 at 8:41 Lesha KLesha K 531 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

Previous answer didn't show exactly how to nest routers. Here is a real-world example, splitted in several controller files.

First, we define some API routes into a controllers/api/foo.js file:

var router = require('koa-router')();

router.get('/', function* () {
    // Return a list of foos
});

router.get('/:id', function* () {
    // Return a specific foo
});

module.exports = router;

Then, on your application router, you can embed it like the following, in a file controllers/index.js:

var router = require('koa-router')();

// Create a new route
router.get('/', function* () {
    this.body = 'Home page';
});

// Nest previous API route
router.get('/api/foo', require('./api/foo').routes());

module.exports = router;

Finally, just use the router into your application index.js:

var koa = require('koa');
var app = koa();
app.use(require('./controllers').routes());
app.listen(process.env.PORT || 3000);

I believe koa-router should do what your needing.

var Router = require('koa-router');

var restApiRouter = new Router({
  prefix: '/api'
});

restApiRouter.get('/', ...); // responds to "/api"
restApiRouter.get('/messages', ...); // responds to "/api/messages"

var router = new Router();
router.get('/', ...); // responds to "/"

app
  .use(restApiRouter.routes())
  .use(router.routes())
  .use(restApiRouter.allowedMethods());
  .use(router.allowedMethods());

Well, maybe not exactly as you expect, but, in my experience, koa-router does that job.

I don't have right now any tested code, but it should look like this

main.js

    var app = require('koa')()
    var port = 8080
    var http = require('http')
    var server = http.createServer(app.callback())
    // Import your main Router
    var mainRouter = require('/app/routes/root')

    //and use its routes and methods
    app.use( mainRouter.routes())
    app.use( mainRouter.allowedMethods())

    server.listen(port, function(){
      console.log ('Listening on port %d, App Ready',port)
    })
 

The Main router definition

/app/routes/root.js

"use strict;"

var router = require('koa-router')();

router.redirect('/', 'index.html')

router.get('/*.html', *blahblah())
 // returns any html on root

// define your admin router here
var adminRouter = require(appRoot+'/app/routes/admin')

// ..and import it into current router
router.use(adminRouter.routes() )
router.use(adminRouter.allowedMethods() )

//  at the end, export myself
module.exports = router

And finally, the Admin section router

/app/routes/admin.js

"use strict;"

// define router here, adding a prefix
var router = require('koa-router')().prefix('/admin/');
// redirect if no file specified
router.redirect('/', 'index.html')

router.get('*.html', function *(next){
    //do your own work
    this.body = something
})

// add More Routes, if needed
router.get('api.html', function *(next){
    if (this.query['status'])
       this.body = statusObject
  
})

// and finally export it
module.exports = router

NOTE: All of the above isn't directly runnable code. It's only a conceptual example

Also note that you can use tons of koa-middleware ( or even write your own: it's not that hard) that maybe could affect koa-router behaviour

发布评论

评论列表(0)

  1. 暂无评论