Deno post method empty request body
Asked Answered
S

1

6

I am currently developing a proof-of-concept REST api app with Deno and I have a problem with my post method (getAll et get working). The body of my request does not contain data sent with Insomnia.

My method :

addQuote: async ({ request, response }: { request: any; response: any }) => {
    const body = await request.body();
    if (!request.hasBody) {
      response.status = 400;
      response.body = { message: "No data provided" };
      return;
    }

    let newQuote: Quote = {
      id: v4.generate(),
      philosophy: body.value.philosophy,
      author: body.value.author,
      quote: body.value.quote,
    };

    quotes.push(newQuote);
    response.body = newQuote;
  },

Request :

insomnia json request

Response :

insomnia json response

I put Content-Type - application/json in the header.
If I return only body.value, it's empty.

Thanks for help !

Saltpeter answered 3/9, 2020 at 16:54 Comment(2)
Are you using oak framework?Tortosa
@Chellappanவ yes I am for the router ! import { Router } from 'https://deno.land/x/oak/mod.ts'Saltpeter
R
6

Since value type is promise we have to resolve before accessing value.

Try this:

addQuote: async ({ request, response }: { request: any; response: any }) => {
    const body = await request.body(); //Returns { type: "json", value: Promise { <pending> } }
    if (!request.hasBody) {
      response.status = 400;
      response.body = { message: "No data provided" };
      return;
    }
    const values = await body.value;
    let newQuote: Quote = {
      id: v4.generate(),
      philosophy: values.philosophy,
      author: values.author,
      quote: values.quote,
    };

    quotes.push(newQuote);
    response.body = newQuote;
  }
Resolution answered 5/9, 2020 at 8:56 Comment(2)
Thanks for answer! The compilation fails because result doesn't exist. I replaced by body and it works!Saltpeter
Worked. Same thing await was missing in my body.value;Margartmargate

© 2022 - 2024 — McMap. All rights reserved.