Returns an undefined value on a post request

658 Views Asked by At

When I make a post request returns - undefined

request:

curl --location --request POST 'http://localhost:8000/api/register?name=Jose&[email protected]&password=123456'
--header 'Content-Type: multipart/form-data; boundary=something'

  export const Register = async (ctx: Context) => {
      const { name, email, password } = await ctx.request.body().value; 

      try {
        
        ctx.response.body = { name: name , email: email , password: password };
    //return: {} undefined

        } catch (err) {
          ctx.response.status = 404;
          ctx.response.body = { msg: 'error' }; 
        }
  }
1

There are 1 best solutions below

3
On

I noticed you've been asking multiple questions about Oak recently. Here's the documentation for the current version of Oak. If you spend some time reading through it thoroughly over a couple of days, I think you will better understand how to use it.

The kind of data that you're transferring is suitable for a simpler encoding scheme like JSON. Here's a self-contained demo:

./so-71455993.ts::

// Server:

import {
  Application,
  Context,
  Router,
  Status,
} from "https://deno.land/x/[email protected]/mod.ts";

const Register = async (ctx: Context) => {
  try {
    const { name, email, password } = await ctx.request.body({ type: "json" })
      .value;

    ctx.response.body = { name, email, password };
  } catch {
    ctx.response.status = Status.BadRequest;
    ctx.response.body = { msg: "error" };
  }
};

const apiRouter = new Router({ prefix: "/api" }).post("/register", Register);

const app = new Application()
  .use(apiRouter.routes())
  .use(apiRouter.allowedMethods());

// This abort signal is just for the demo
// so that the client can stop the server
// instead of needing to ctrl+c every time we run this demo
const ac = new AbortController();
const { signal } = ac;

app.listen({ port: 8080, signal });

// Client:

type RegistrationOptions = Record<"email" | "name" | "password", string>;

async function postRegistration(options: RegistrationOptions): Promise<void> {
  try {
    const url = new URL("http://localhost:8080/api/register");
    const body = JSON.stringify(options);

    const request = new Request(url.href, {
      body,
      headers: new Headers([["content-type", "application/json"]]),
      method: "POST",
    });

    const response = await fetch(request);

    console.log("Success", {
      body: await response.json(),
      status: response.status,
    });
  } catch (ex: unknown) {
    console.error("Error", ex);
  }
}

await postRegistration({
  email: "[email protected]",
  name: "Jose",
  password: "123456",
});

// Stop the server
ac.abort();

$ deno run --allow-net ./so-71455993.ts
Check file:///Users/deno/so-71455993.ts
Success { body: { name: "Jose", email: "[email protected]", password: "123456" }, status: 200 }