unjs / h3

⚡️ Minimal H(TTP) framework built for high performance and portability

Home Page:https://h3.unjs.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't readBody on a GET request

julesfrn opened this issue · comments

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 :

assertMethod(event, PayloadMethods);

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

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