'Returns an undefined value on a post request
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' };
}
}
Solution 1:[1]
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 }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jsejcksn |
