Netlify表单联系表单提交404错误

时间:2020-09-06 11:46:07

标签: reactjs gatsby netlify netlify-form

我无法通过使用Netlify-Forms提交我的联系页,但出现404错误。

我的格式如下:-

<form name="Portfolio_Contact" 
      method="POST" 
      data-netlify="true"
      data-netlify-honeypot="bot-field"
      action="/thank-you">
    <div className="form-group">
      <input
        type="text"
        name="name"
        placeholder="name"
        className="form-control"
      />
      <input
        type="email"
        placeholder="email"
        name="email"
        className="form-control"
      />
      <textarea
        name="message"
        rows="5"
        placeholder="message"
        className="form-control"
      ></textarea>
      <div data-netlify-recaptcha="true"></div>
    </div>
    <button type="submit" className="submit-btn btn">
      send me your message
    </button>
  </form>

提交时,我首先遇到404错误,然后按预期获得了我的感谢页面。

我做错什么了吗?我可以在“表单”部分中看到我的“ Portfolio_Contact”。

感谢您的帮助和时间。

1 个答案:

答案 0 :(得分:1)

您有一个reCAPTCHA设置,但是您的表单不期望这样做,因为您的<form>标记中没有定义。只需添加:

<form name="Portfolio_Contact" 
      method="POST" 
      data-netlify="true"
      data-netlify-honeypot="bot-field" 
      data-netlify-recaptcha="true"
      action="/thank-you">

发现data-netlify-recaptcha="true"。您可以在Netlify documentation for reCAPTCHA 2中找到更多信息。

我正在网络上获取此信息:- Referrer Policy: strict-origin-when-cross-origin

除了<form>标签上的此配置之外,您还需要设置POST动作配置。 Netlify在他们的响应中有点奇怪,404并不意味着您的表单不存在,这意味着请求失败。我通常会应用已发布的确切<form>配置,但是会添加一个自定义的提交句柄函数来设置请求配置:

<form name="Portfolio_Contact" 
      method="POST" 
      data-netlify="true"
      data-netlify-honeypot="bot-field" 
      data-netlify-recaptcha="true"
      action="/thank-you">
    <div className="form-group">
      <input
        type="text"
        name="name"
        placeholder="name"
        className="form-control"
      />
      <input
        type="email"
        placeholder="email"
        name="email"
        className="form-control"
      />
      <textarea
        name="message"
        rows="5"
        placeholder="message"
        className="form-control"
      ></textarea>
      <div data-netlify-recaptcha="true"></div>
    </div>
    <button type="submit" className="submit-btn btn" onClick={handleSubmit}>
      send me your message
    </button>
  </form>

您的handleSubmit函数:

  const handleSubmit = event => {
    event.preventDefault();

   // do your verifications and checks
   if(!verified) return false    

    const REQUEST_PARAMETERS = {
      method: `POST`,
      headers: { 'Content-Type': `application/x-www-form-urlencoded` },
      body: encode({ ...data }), //your data here. Needs to have your form-name attribute set
    };

    fetch(`/`, REQUEST_PARAMETERS)
      .then(() => {
        console.log(`OK`);
      })
      .catch(error => alert(error));
  };

注意:您的请求在您的本地环境中无效

此配置很重要,因为它设置了请求的标头,这是您的示例失败的原因。

您可以在此DEV article中检查样品。