typescriptrestrequestdenooak

TypeError - ctx.request.body is not a function


I am trying making a simple RESTApi using Deno and Oak. Why am I getting this error

TypeError - ctx.request.body is not a function
request: { url: "http://localhost:8000/todos", method: "POST", hasBody: true }
response: { status: 500, type: "text", hasBody: true, writable: true }

This is the part of the code where I am getting this error.

import { Router } from 'https://deno.land/x/oak@v16.0.0/mod.ts';
const router = new Router();

interface Todo {
  id: string;
  text: string;
}

let todos: Array<Todo> = [];

router.get('/todos', (ctx, _) => {
  ctx.response.body = { todos: todos };
});

router.post('/todos', async (ctx) => {
  const reqBody = await ctx.request.body(); <--here
  console.log(reqBody);
});

router.put('/todos/:todoId', (ctx, _) => {});

router.delete('/todos/:todoId', (ctx, _) => {});

export default router;

Here is my app.ts file

import { Application } from 'https://deno.land/x/oak/mod.ts';
import todoRoutes from './routes/todos.ts';

const app = new Application();

app.use(todoRoutes.routes());
app.use(todoRoutes.allowedMethods());

await app.listen({ port: 8000 });

I have searched all the answers on the internet. Everywhere they are using ctx.request.body()

But when I use it I am getting the error.


Solution

  • The body usually needs to be used with a method like ctx.request.body.json() or ctx.request.body.form().

    https://deno.land/x/oak@v16.1.0#request-body

    Edit: This was a newer update as far as I'm aware. The docs say with Oak 13.