honojs / middleware

monorepo for Hono third-party middleware/helpers/wrappers
https://hono.dev
474 stars 169 forks source link

Malformed JSON in request body #799

Closed adityabrahmankar closed 3 weeks ago

adityabrahmankar commented 4 weeks ago

Hey !

I am using zValidator middleware and even after passing the headers for content-type as application/json I am getting the error Malformed JSON in request body. Also the image shows the content-type as plain-text πŸ‘‡

image

// use-create-workspace.ts

import { client } from "@/lib/rpc";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { InferRequestType, InferResponseType } from "hono";
import { useRouter } from "next/navigation";

type ResponseType = InferResponseType<typeof client.api.workspaces["$post"], 200>
type RequestType = InferRequestType<typeof client.api.workspaces["$post"]>["json"]

export const useCreateWorkspace = () => {
  const queryClient = useQueryClient()
  const router = useRouter()

  const mutation = useMutation<
    ResponseType,
    Error,
    RequestType
  >({
    mutationFn: async (json) => {
      const response = await client.api.workspaces.$post({
        json
      },{
        headers: {
          "Content-Type": "application/json"
        }
      })

      if (!response.ok) {
        throw new Error("Something went wrong");
      }

      return await response.json()
    },
    onSuccess() {
      router.refresh()
      queryClient.invalidateQueries({ queryKey: ["workspaces"] })
    },
  })

  return mutation
}
// mutate function

  const onSubmit = async (values: z.infer<typeof createWorkspaceSchema>) => {

    mutate({
      name: values.name
    }, {
      onSuccess() {
        toast.success(` Workspace created successfully`)
      }
    })
.post(
    "/",
    verifyAuth(),
    zValidator(
      "json",
      z.object({
        name: z.string().min(1).max(20)
      }),
    ),
    async (c) => {
      const auth = c.get("authUser")
      const { name } = c.req.valid("json")

      if (!auth.token?.id) {
        return c.json({ error: "Unauthorized" }, 401)
      }

      ...somedata

      return c.json({
        some data
      })
    }
  )
985563349 commented 3 weeks ago

I had the same problem.

yusukebe commented 3 weeks ago

Hi @adityabrahmankar @985563349

Please share a minimal project to reproduce it.

adityabrahmankar commented 3 weeks ago

Tried again no issue this time !!

985563349 commented 3 weeks ago

@yusukebe I found that calling await c.req.json() throws Malformed JSON in request body after using verifyAuth middleware. sorry, this example is a bit complicated and I don't know how to organize it yet.

I use the package version: β€œhonoβ€œ:”^4.6.7”, β€œ@hono/auth-jsβ€œ:”^1.0.13”,