unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability
https://h3.unjs.io/
MIT License
3.69k stars 219 forks source link

Can't readBody on a GET request #749

Closed julesfrn closed 4 months ago

julesfrn commented 6 months ago

Hello,

I am getting an error when I use the readBody() function on a get Request. After checking out the implementation I realised that it's a normal behaviour as it is specified in the code : https://github.com/unjs/h3/blob/58e33ff00b1db1cf86a780bf8b152c3f7e573350/src/utils/body.ts#L44

I wonder why we want this specific behaviour, and not just return undefined like the function does for a POST request with no body.

I am not trying to make GET requests with a payload but I made a custom route array and registered them generically in my h3 router by looping on my array of routes so I use the readBody function for any routes no matter the verb.

const wrapHandler = (handler: HTTPHandler) => async (event: H3Event<EventHandlerRequest>) => {
    const request: HTTPRequest = {
      payload: await readBody(event),
      query: getQuery(event),
      params: getRouterParams(event)
    }
    const { status, body } = await handler(request)
    setResponseStatus(event, status)
    return body
  }

  routes.forEach(({ path, handler, method }) => {
    console.log(`Registering route : ${method} /api${path}`)
    nitroApp.router.use(`/api${path}`, defineEventHandler(wrapHandler(handler)), method)
  })

I feel like I should be able to do this but if not, do you have any suggestions on how I should handle this ? I dont want to have to write an if ('post' || 'put' || 'patch'....) because I'm not supposed to know what h3 considers as a "PayloadMethod". Maybe h3 should expose a method isPayloadMethod() so that i can use readBody() onfy if the previous function returns true

Thank you for your answers

pi0 commented 4 months ago

h3 v2 will return empty values when reading body in get requests