Search code examples
node.jskoakoa-router

Why koa-router sends 404?


I'm using a koa-router, koa-views and sequelize. Data comes from a database, but the status = 404. What am I doing wrong?

router.get('/', function *() {
  var ctx = this;

  yield models.drivers.findAll({
    where: {
      userId: ctx.passport.user.id
    }
  }).then(function(drivers) {
    ctx.render('driversSearch', {
      drivers: drivers
    });
  });
});

Solution

  • Looks like you're not taking advantage of Koa's coroutine features. Your code can be rewritten like this:

    router.get('/', function *() {
      var drivers = yield models.drivers.findAll({
        where: {
          userId: this.passport.user.id
        }
      });
    
      this.render('driversSearch', {
        drivers: drivers
      });
    });
    

    Koa uses the co library under the hood. If you yield a promise, the generator function will pause and then resume when the promise is fulfilled.