Reputation: 31
var path = require('path')
var route= require('koa-route');//路由
app.use(route.get('/api/*',api.before));
I can't use it for this,how should I use wildcards in koa-route? Or,which other can do ?
Upvotes: 3
Views: 5483
Reputation: 1
For
app.use(route.get('/api/*',api.before));
In api.before:
/api/a/b/c
==>
ctx.params[0] ; // => a/b/c
Upvotes: 0
Reputation: 9454
I've been using https://github.com/alexmingoia/koa-router. I found koa-route
too limiting.
It allows RegExp matching:
app.use(require('koa-router')(app));
// Matches '/test', '/test/foo/bar', '/test/foo/bar?page=2'
// but does NOT match '/test-route'
app.get(/^\/test(?:\/|$)/, function*() {
this.body = 'Test';
});
It looks to me like you're trying to attach middleware on /api/*
that will run before all /api/*
routes (like for authentication). This is how you can do that with koa-router:
///////////////////////////////////////////////////////////////////
// File: routes/api.js
///////////////////////////////////////////////////////////////////
var Router = require('koa-router');
// Create a router instance to bind middleware/routes to.
// Our module will export it so that our main routes.js file can
// mount it to our app.
var router = new Router();
// Middleware that ensures that a user is logged in for
// all routes attached to this router.
router.use(function*(next) {
this.assert(this.currentUser, 403);
yield next;
});
router.get('/test', function*() {
this.body = 'You went to /api/test';
});
module.exports = router;
///////////////////////////////////////////////////////////////////
// File: routes.js
///////////////////////////////////////////////////////////////////
var app = require('koa')();
var mount = require('koa-mount');
var apiRouter = require('./routes/api');
app.use(mount('/api', apiRouter.routes()));
If you navigate to /api
, it'll be handled by the /
handler in the router since you mounted it to /api
, and it will return 403 unless you are logged in.
Upvotes: 4