NEXT JS 的 req.body 未定义。

4

不确定我做错了什么?

尝试将表单数据上传到我的Supabase时,我遇到了undefined问题。该数据传递到API时为未定义,但当我将其传递到函数中并在提交处理程序中打印要发送到API的内容时,它却正常输出。

export const Quote = () => {
  const [formIsValid, setFormIsValid] = useState(false);
  //----------------------------_FORM VALIDATION------------------------------------
  const {
    value: firstName,
    inputBlurChangeHandler: firstNameBlur,
    isValid: firstNameValid,
    hasError: firstNameInputHasError,
    valueChangeHandler: firstNameChangeHandler,
    reset: resetFirstName,
  } = useInput((value) => value.trim() !== "");



**hooks & useEffect removed to shorten question they are same as above but different names**

  console.log(formIsValid, "FORM IS VALID");


  const formSubmitHandler = async (event) => {
    event.preventDefault();

    //UNDEFINEDS
    await fetch("api/dbhandler", {
      method: "POST",
      body: {
        firstname: firstName,
        secondname: secondName,
        street: streetAddress,
        phone: phoneNumber,
        email: emailAddress,
        postal: postalCode,
        about: quoteDescription,
      },
      headers: {
        "Content-Type": `text/plain`,
      },
    });
  };

API在req.body中出现未定义,但如果我在提交处理程序中记录控制台日志,则值将传递到函数中,不确定我做错了什么

import { supabase } from "../../utils/supabaseClient";

const supabaseApiHandler = async (req, res) => {
  console.log(req.body.firstname);
  if (req.method === "POST") {
    const firstname = req.body.firstname;
    const secondname = req.body.secondname;
    const email = req.body.email;
    const street = req.body.street;
    const postal = req.body.postal;
    const phone = req.body.phone;
    const about = req.body.about;

    const { data, error } = await supabase.from("quotes").insert([
      {
        firstname,
        secondname,
        email,
        street,
        postal,
        phone,
        about,
      },
    ]);
  }

  res.status(200).json({ name: "test" });
};

export default supabaseApiHandler;

1
尝试使用 body: JSON.stringify(bodyData) - user16435030
没有运气 :( - KeoooDev
2
可能是因为您还告诉服务器,您的内容不是JSON,而是文本。将其更改为"Content-Type": "application/json" - user16435030
我修复了代码,我创建了一个常量reqBody,内容如下:{ firstname:firstName, secondname:secondName, //接下来是其他... }; - KeoooDev
await fetch(api/dbhandler, { method: "POST", body: JSON.stringify(reqBody), - KeoooDev
1个回答

16

如果在API路由中禁用了body parser,那么req.body将为空。

我无意中将此代码留在其中,而没有使用另一个body parser。

export const config = {
  api: {
    bodyParser: false,
  },
};

该死,我浪费了一个小时在与Postman和Validator周旋中。 - Anirudh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接