Reading request body in middleware without consuming It? #1417
Unanswered
Manouchehri
asked this question in
Q&A
Replies: 1 comment
-
from what i can tell, hono parses the body via array buffer, updating a cache after consuming the body; see #1499. using the hono validator helper code as reference, i arrived at the following solution, which populates the cached buffer in the middleware, allowing the body to also be consumed in a handler hono/src/validator/validator.ts Line 81 in 81264a9 initially i tried to simply clone the request, but the body would get stripped. this may be related to bun: oven-sh/bun#6348. in any case, the below should work app.use(async (c, next) => {
const arrayBuffer = await c.req.arrayBuffer();
c.req.bodyCache.arrayBuffer = arrayBuffer;
const body = await new Response(arrayBuffer).text()
await next()
})
app.get('/', (c) => {
const body = await c.req.json()
console.log(body) // { ... }
return c.text('ok')
}) |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Question
Question taken from: https://discord.com/channels/1011308539819597844/1011308539819597847/1148952087070265416
Answer
Beta Was this translation helpful? Give feedback.
All reactions