skip to Main Content

I was trying to send a post request to my api. However trying to access the request body in the route handler causes the error below:

Code:

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

Error:
Argument of type ‘ReadableStream’ is not assignable to parameter of type ‘string’.

Any help would be appreciated

2

Answers


  1. I think The issue is just with the Type. Try importing NextApiRequest from next instead of Request

    import type { NextApiRequest, NextApiResponse } from "next";
    
    export default async function handler(
      req: NextApiRequest,
      res: NextApiResponse,
    ) {
      if (req.method !== "POST") {
        res.status(405).send({ message: "Method not allowed" });
      }
      const body = req.body;
    
      // There is your body
    
      
    }
    Login or Signup to reply.
  2. You need to call json() on the Request object.

    export async function POST(request: Request) {
      const res = await request.json() // res now contains body
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search