Reading request body after passing it to a handler with itty router

I am building my apps api with workers… kv… and DO…

I am also user itty router to handle routes. When I pass my request to a handler function I can’t directly access the body without first creating a new request… even though I am not modifying the request… I am only trying to read the body sent.

Why?

I am very confused as why this is the case. At first I found a thread that said to clone it but then I got a warner in wrangler to create a new request.

Thanks for any help.

Assuming you’re trying to use a middleware handler, this should work:

const logUrl = request => console.log(request.url)
router.get('/someendpoint', logUser, () => new Response('You have reached some endpoint.'))

You don’t have to return a value or change anything, just use the request object that’s passed through to the middleware.

Sorry for such a late response. I got caught with another project and had to get that done.

I mistyped my question and let me share some code too.

export async function handleContactForm(request: Request): Promise<Response> {
  const newResObj = new Response(request.body)
  const body: ContactFormReqBody = await newResObj.json()

  console.log(body)

  return new Response('Will will be in touch')
}

I am creating a new Response object with the request.body and then I am able to await that data.

But if I try to just await the await request.json()… I can’t get the data in my request body.

This does NOT work:

export async function handleContactForm(request: Request): Promise<Response> {
  const body: ContactFormReqBody = await request.json()

  console.log(body)

  return new Response('Will will be in touch')
}

My console tells me it’s an unknown object.

Thanks for any help if possible on understand why I have to build a new Response.