axios Next js Routes处理程序中未定义方法参数

yfjy0ee7  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(97)

无法识别为什么我的参数未定义

我目前正在学习如何使用新的Nextjs API路由,但每次我尝试在HTTP方法中使用参数时,都会得到一个错误,说它是未定义的。
我使用prisma作为我的ORM和PlanetScale作为我的数据库。
下面是我定义的API路由的一个示例:

import { NextRequest, NextResponse } from "next/server";
import prisma from "@/lib/prisma";

type params = {
  req: NextRequest;
  res: NextResponse;
};

export const POST = async ({ req }: params) => {
  console.log(req);
  const result = await prisma.meetUp.create({
    data: {
      title: "some title here because I can't get the request body",
      description: "pls help me",
    },
  });

  return NextResponse.json(result);
};

每个req日志都在说Undefined
下面是使用此post方法的前端组件:

"use client";

import axios from "axios";
import { ChangeEvent, useState } from "react";

const MeetUpForm = () => {
  const [meetUp, setMeetUp] = useState({ title: "", description: "" });

  const submitData = async (e: React.SyntheticEvent) => {
    e.preventDefault();
    try {
      await axios.post("api/meet", meetUp);
    } catch (error) {
      console.error(error);
    }
  };

  const changeValue = (e: ChangeEvent<HTMLInputElement>) => {
    setMeetUp({
      ...meetUp,
      [e.target.name]: e.target.value,
    });
  };

  return (
    <form className="border-solid border-black" onSubmit={submitData}>
      <h1>Create new meet up</h1>
      <input
        type="text"
        name="title"
        placeholder="title"
        onChange={changeValue}
        value={meetUp.title}
      />
      <input
        name="description"
        type="text"
        placeholder="description"
        onChange={changeValue}
        value={meetUp.description}
      />
      <input type="submit" onChange={changeValue} value="Create" />
    </form>
  );
};

export default MeetUpForm;

我试图让这个参数在数据库中发布请求主体。

clj7thdc

clj7thdc1#

假设您使用的是app路由器,并且答案中共享的代码来自route.ts文件,
从以下位置更改POST处理程序:

export const POST = async ({ req }: params) => {

收件人:

export const POST = async (req: Request) => {

注意,req现在是第一个参数。如果你需要从中获取查询参数,你可以这样做:

export const POST = async (req: Request) => {
  const { searchParams } = new URL(req.url)
  const id = searchParams.get('id')
}

相关问题