3
export async function getPlaces(ctx, next) {
    const { error, data } = await PlaceModel.getPlaces(ctx.query);
    console.log(error, data);
    if (error) {
        return ctx.throw(422, error);
    }
    ctx.body = data;
}

Koa everytime sends 404 status and empty body, what i'm doing wrong ?

BladeMight
  • 2,670
  • 2
  • 21
  • 35

5 Answers5

5

In seems that, await does not really "wait" and therefore returns too early (this results in a 404 error).

One reason for that could be that your PlaceModel.getPlaces(ctx.query) does not returns a promise. So it continues without waiting on results from getPlaces.

Carl Manaster
  • 39,912
  • 17
  • 102
  • 155
Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
3

I also had this issue, and resolved it by adding :

ctx.status = 200;

directly below

ctx.body = data;

Kris Randall
  • 686
  • 1
  • 7
  • 12
1

You've got to wire up your function with the router. Here's a little example how it works:

import * as Koa from "koa";
import * as Router from "koa-router";

let app = new Koa();
let router = new Router();

async function ping(ctx) {
  ctx.body = "pong";
  ctx.status = 200;
}

router.get("/ping", ping);

app.use(router.routes());
app.listen(8080);
shadeglare
  • 7,006
  • 7
  • 47
  • 59
1

Maybe you have middleware that is being triggered before this async function, but that middleware isn't async.

  1. If you have any non-async middleware that gets called before this function, convert it to async.

  2. Instead of calling next(); in the async middleware, call await next(); even if it is the last line of the middleware function.

TxRegex
  • 2,347
  • 21
  • 20
0

in my case while using koa router i had forgotten to add

app.use(router.routes())

just above

app.listen(port)
Brian Mutiso
  • 299
  • 6
  • 10