koajs / route

Simple route middleware

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

route catch all phase, wildcat route is missing.

mattma opened this issue · comments

I am trying to have a * - wildcat route to catch everything. I do not think it is actually supported by koa yet. But express build-in router does support this feature.

I tried with example.js which comes with this project with a little modification.

var pets = {
  list: function *(){
    var names = Object.keys(db);
    this.body = 'pets: ' + names.join(', ');
  },

  show: function *(name){
    var pet = db[name];
    if (!pet) return this.throw('cannot find that pet', 404);
    this.body = pet.name + ' is a ' + pet.species;
  },

  all: function *() {  // <= addition
    this.body = 'show me some content';
  }
};

app.use(r.get('/pets', pets.list));
app.use(r.get('/pets/:name', pets.show));
app.use(r.get('*', pets.all));  // <= addition

The behavior that I am looking for, If I do curl http://localhost:3000, I should see 'show me some content', or any path except /pet and /pet/:name.

I do know there is a project called koa-router. Not sure that it supports or not, but it does say it works like express router.

app.use(r.get('(.*)', pets.all));  // <= addition

Indeed, it works.

十分感谢。杭州现在这么多牛人,幸会幸会!有时间多交流!