Koa路由器路由url不存在

我不敢相信这样做并不容易。 我希望redirect让我们说;

www.example.com/this-url-does-not-exist 

 www.example.com/ 

必须有一种方法,所有与koajs nodejs网站不能崩溃? inheritance人我的路由器(我用koa与路由器):

 router .get('/', function* (next) { this.body = "public: /"; }) .get('/about', function* (next) { this.body = "public: /about"; }) .get('*', function* (next) { // <--- wildcard * doesn't work this.body = "public: *"; }); 

不要告诉我使用正则expression式,我一直在尝试,并与他们,这意味着手动更新expression式,当添加url等,这不是我所期待的,再加上它不工作,因为JavaScript不支持负面的后顾之忧。

如果你不喜欢正则expression式做这样的事情:

 var koa = require('koa'), router = require('koa-router')(), app = koa(); router.get('/path1', function *(){ this.body = 'Path1 response'; }); router.get('/path2', function *(){ this.body = 'Path2 response'; }); app.use(router.routes()) app.use(router.allowedMethods()); // catch all middleware, only land here // if no other routing rules match // make sure it is added after everything else app.use(function *(){ this.body = 'Invalid URL!!!'; // or redirect etc // this.redirect('/someotherspot'); }); app.listen(3000); 

JAMES MOORES ANSWER是正确的; 不要听我的话!

 publicRouter .get('/', function* (next) { console.log('public: /'); this.body = 'public: /'; }) .get('/about', function* (next) { console.log('public: /about'); this.body = 'public: /about'; }) .get(/(|^$)/, function* (next) { // <--- important that it is last console.log('public: /(|^$)/'); this.body = 'public: /(|^$)/'; }); 

Koa路由器未能通知.get取决于它们在代码中添加的顺序 。 所以把它与正则expression式/(|^$)/工程结束。

但是,当使用koa-mount挂载其他路由器时,这会干扰。