为什么我在Prisma中传递body数据时请求body为空

问题描述 投票:0回答:1

我使用 Prisma 在数据库中存储数据,并使用 MySql。这个应用程序由 nextjs 和 typescript 创建。我创建了 api,它工作正常。但是当我想保存一些由api发送的数据时,request.body为空。当我静态设置该值时,它会存储。

const prisma = new PrismaClient();

export async function GET() {
  const allCenters = await prisma.centers.findMany();
  return NextResponse.json(allCenters);
}

export async function POST(req: NextResponse) {
  try {
    const { name, username, password, address }: any = req.body;
    await prisma.centers.create({
      data: {
        name: String(name),
        username: String(username),
        password: String(password),
        address: String(address),
      },
    });
    return Response.json("done");
  } catch (error) {
    console.log(error);
    return Response.json("error");
  }
}

async function sendHandler() {
    try {
      const response = await axios.post(
        "http://localhost:3000/api/centers",
        newCenter,
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      console.log("Data sent successfully:", response.data);
    } catch (error) {
      console.error("Error sending data:", error);
    }
  }

reactjs typescript next.js prisma
1个回答
0
投票

使用 body-parser 并添加对 req.method===POST 的检查

类似这样的-

import { NextApiRequest, NextApiResponse } from 'next';
import bodyParser from 'body-parser';
 
const jsonParser = bodyParser.json();

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') { 
    jsonParser(req, res, async () => {
      try {
        const { name, username, password, address }: any = req.body;
        await prisma.centers.create({
          data: {
            name: String(name),
            username: String(username),
            password: String(password),
            address: String(address),
          },
        });
        return res.json("done");
      } catch (error) {
        console.log(error);
        return res.status(500).json("error");
      }
    });
  } else {
    return res.status(405).end();  
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.