capedcoder
capedcoder
HHono
Created by duydang on 9/27/2024 in #help
Using both `c.body` and `c.json` in an endpoint results in `response.json()` of `Promise<unknown>`
A null body is not json, it's an empty body. You first need to check to see if the response is JSON, then you can read the json if it exists. Something like this:
app.get("/test", (c) => {
if (Math.random() < 0.5) return c.body(null, 204);
return c.json({ status: "ok" }, 200);
});

const response = await app.request("/test");
const isJson = response.headers.get("content-type")?.startsWith("application/json") || false;
if (isJson) {
console.log(await response.json());
}
app.get("/test", (c) => {
if (Math.random() < 0.5) return c.body(null, 204);
return c.json({ status: "ok" }, 200);
});

const response = await app.request("/test");
const isJson = response.headers.get("content-type")?.startsWith("application/json") || false;
if (isJson) {
console.log(await response.json());
}
2 replies