我的 next.js 14 项目中的 Netlify 表单提交问题

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

我在将 Netlify 的表单提交与我的 Next.js 14 项目配合使用时遇到问题。我遵循了 Netlify 的建议,在 Netlify 中激活了表单提交,并在公共文件夹中设置了隐藏表单。这是我到目前为止所拥有的:

公共文件夹中的__forms.html:

<html>
  <head></head>
  <body>
    <form name="contact" data-netlify="true" hidden>
      <input type="hidden" name="form-name" value="contact" />
      <input name="name" type="text" />
      <input name="email" type="email" />
      <input name="company" type="text" />
      <input name="phone" type="tel" />
      <input name="message" type="text" />
    </form>
  </body>
</html>

ContactForm 组件:

import { useState } from 'react';

function ContactForm() {
  const [status, setStatus] = useState(null);
  const [error, setError] = useState(null);

  const handleFormSubmit = async (event) => {
    event.preventDefault();
    try {
      setStatus('pending');
      setError(null);
      const form = event.target;
      const formData = new FormData(form);
      const res = await fetch('/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(formData).toString(),
      });
      if (res.ok) {
        setStatus('ok');
        form.reset(); // Clear the form inputs
      } else {
        throw new Error(`Error: ${res.status} ${res.statusText}`);
      }
    } catch (e) {
      setStatus('error');
      setError(e.message);
    }
  };

  return (
    <form
      name="contact"
      method="POST"
      data-netlify="true"
      onSubmit={handleFormSubmit}
    >
      <input type="hidden" name="form-name" value="contact" />
      <input type="text" name="name" required placeholder="Name" />
      <input type="email" name="email" required placeholder="Email" />
      <input type="text" name="company" required placeholder="Company" />
      <input type="tel" name="phone" required placeholder="Phone" />
      <input type="text" name="message" required placeholder="Message" />
      <button type="submit" disabled={status === 'pending' || status === 'ok'}>
        {status === 'ok' ? 'Message sent' : status === 'pending' ? 'Sending...' : 'Send message'}
      </button>
      {status === 'error' && <div>Error: {error}</div>}
    </form>
  );
}

export default ContactForm;

尽管如此设置,表单提交并未记录在 Netlify 中。我已确保在 Netlify 中启用表单提交。我可能遗漏了什么或做错了什么?

我正在使用 Next.js 14.0.4。

表单在网站上正确显示,但提交内容未显示在 Netlify 的表单仪表板中。 Netlify 还会检测表单(可能是我的公共文件夹中的 html 表单),但不会检测任何提交。

我尝试阅读 Netlify 的文章:Netlify 上的 Next.js (https://docs.netlify.com/frameworks/next-js/overview/) 及其入门模板,特别是 __forms.html (https:/ /github.com/netlify-templates/next-platform-starter/blob/main/public/__forms.html)文件和feedback-form.jsx(https://github.com/netlify-templates/next- platform-starter/blob/main/components/feedback-form.jsx) 文件。

我希望表单提交出现在 Netlify 的表单仪表板中。然而,尽管进行了设置,但提交内容并未被记录。该表单在网站上正确显示,但提交内容在 Netlify 中不可见。

html forms next.js netlify
1个回答
0
投票
在 __forms.html 中添加 method="post" ,在尝试了两天后为我解决了这个问题
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.