Búsqueda de sitios web

reactjs - Cómo acceder al cuerpo de la solicitud en el manejador de rutas de nextjs 13.2


Estaba intentando enviar una solicitud POST a mi API. Sin embargo, intentar acceder al cuerpo de la solicitud en el manejador de rutas causa el siguiente error:

Código:

export async function POST(request: Request) {
  const postBody: postProps = JSON.parse(request.body) // 👈 Error here on request.body
  ...
}

Error: El argumento de tipo 'ReadableStream' no se puede asignar al parámetro de tipo 'string'.

Cualquier ayuda sería apreciada

Respuesta #1

Necesitas llamar a json() en el objeto Request.

export async function POST(request: Request) {
  const res = await request.json() // res now contains body
}

Respuesta #2

Tenía problemas para verificar el webhook de Clerk en Next.js usando App Router.

Lo siguiente me funcionó.

import { Webhook } from "svix";

export async function POST(req: NextRequest) {
  const svix_id = req.headers.get("svix-id") ?? '';
  const svix_timestamp = req.headers.get("svix-timestamp") ?? '';
  const svix_signature = req.headers.get("svix-signature") ?? '';
  
  const body = await req.text(); // This get's the raw body as a string
  
  const sivx =  new Webhook("your_secret_key_here")

  const payload = sivx.verify(body, {
    "svix-id": svix_id,
    "svix-timestamp": svix_timestamp,
    "svix-signature": svix_signature,

  });

  // The payload is the json.
  console.log(payload);

  // The rest of your code

  return NextResponse.json(null, { status: 200 })

}


Para referencia:

https://developer.mozilla.org/es/docs/Web/API/Response/text

Artículos relacionados