繁体   English   中英

数据未发布到 NextJS API 路线

[英]Data not posting to NextJS API Route

我在 NextJS 页面上有一个简单的表单,数据存储在 state 中:

const [bookingInfo, setBookingInfo] = useState({
    name: "",
    email: "",
    phone: "",
  });

const handleChange = (e) => {
    setBookingInfo({ ...bookingInfo, [e.target.name]: e.target.value });
 };

<form onSubmit={handleSubmit} className="flex-col">
            <input
              type="text"
              name="name"
              value={bookingInfo.name}
              placeholder="name"
              onChange={handleChange}
            />
            <input
              type="text"
              name="email"
              value={bookingInfo.email}
              placeholder="email"
              onChange={handleChange}
            />
            <input
              type="text"
              name="phone"
              value={bookingInfo.phone}
              placeholder="phone"
              onChange={handleChange}
            />
            <button>Submit</button>
          </form>

在提交时,我通过 function 在我的上下文中将数据保存在 localStorage 中(它显示完美),并将数据(希望)发送到我的 API 路由:

const handleSubmit = async (e) => {
    e.preventDefault();

    saveCustomerDetails(bookingInfo);

    const response = await fetch("/api/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(bookingInfo),
    });

    console.log(response);
  };

我现在在/api/checkout.js的 API 路由中的所有内容是:

export default async function handler(res, req) {
  try {
    console.log(req.body);
  } catch (error) {}
}

但是,控制台记录了“未定义”,并且我收到警告undefined API resolved without sending a response for /api/checkout, this may result in stalled requests. 有什么想法吗?

您的 API 处理程序的 arguments 顺序错误 - reqres之前。 此外,您正在API resolved without sending a response for /api/checkout, this may result in stalled requests. 因为您没有使用res发送任何响应

所以你的代码应该是:

export default async function handler(req, res) {
  try {
    console.log(req.body);
    res.status(200).json({
       message: 'Success', // just an example
    });
  } catch (error) {}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM