NextJS + Netlify Form | Form Submission causes HTTP Error 405

378 Views Asked by At

I have a simple form on my frontpage build using this tutorial here.

Here is the code block for my ContactForm Component:

import React, { useState } from "react";
import { useRouter } from "next/router";
import styles from '../styles/Contact.module.scss'

const ContactForm = ({ contact }) => {

    const [submitterName, setSubmitterName] = useState("");
    const router = useRouter();
    const confirmationScreenVisible =
        router.query?.success && router.query.success === "true";
    const formVisible = !confirmationScreenVisible;

    const ConfirmationMessage = (
        <React.Fragment>
            <p>
                Thank you for submitting this form. Someone should get back to you
                within 24-48 hours.
            </p>

            <button
                onClick={() => router.replace("/", undefined, { shallow: true })}
            >
                Submit Another Response
            </button>
        </React.Fragment>
    );

    const theContactForm = (
        <form
            name="contact-form"
            method="POST"
            action="/?success=true"
            data-netlify="true"
            netlify-honeypot="bot-field"
        >
            <input type="hidden" name="subject" value={`Prospekti ${submitterName} otti yhteyttä Juhokoli.fi`} />
            <input type="hidden" name="contact-form" value="contact-form" />
            <input type="hidden" name="bot-field" />
            <div className={styles.formControl}>
                <label htmlFor="fullName">Nimi *</label>
                <input
                    placeholder="Nimi *"
                    type="text"
                    name="fullName"
                    id="fullName"
                    autoComplete="name"
                    onChange={(e) => setSubmitterName(e.target.value)}
                    required
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="tel">Puhelinnumero *</label>
                <input
                    placeholder="Puhelinnumero *"
                    type="tel"
                    autoComplete="tel"
                    name="tel"
                    id="tel"
                    required
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="email">Sähköposti</label>
                <input
                    placeholder="Sähköposti"
                    type="email"
                    autoComplete="email"
                    name="email"
                    id="email"
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="message">Viesti</label>
                <textarea
                    placeholder="Viesti"
                    name="message"
                    id="message"
                />
            </div>
            <div className={styles.formControl}>
                <button
                    type="submit"
                    className="btn">
                    {contact.CTA}
                </button>
            </div>
        </form>
    )


    return (
        <section id={styles.formSection}>
            <div id="yhteydenotto" className={styles.formContainer}>
                {formVisible ? theContactForm : ConfirmationMessage}
            </div>
        </section>
    )
}

export default ContactForm

And this ContactForm is then rendered on my Index Page like this:

    const Index = ({ meta, hero, themes, references, faq, contact }) => {

  useEffect(() => {
    if (window.netlifyIdentity) {
      window.netlifyIdentity.on('init', (user) => {
        if (!user) {
          window.netlifyIdentity.on('login', () => {
            document.location.href = '/admin/'
          })
        }
      })
    }
  }, [])

  return (
    <>
      <Meta
        meta={meta}
      />
      <Script src="https://identity.netlify.com/v1/netlify-identity-widget.js"></Script>
      <main id="home">
        <Hero
          hero={hero}
        />
        <ThemeBlock themes={themes} />
        <ReferenceList references={references} />
        <Faq faq={faq} />
        <div className="container ContactContainer">
          <ContactDetails contact={contact} />
          <ContactForm contact={contact} />
        </div>
      </main>
    </>
  )
}

export default Index

You can test my site live here: https://koli22.netlify.app/

However on the live site it simply states “Page not found”, while on the local development it first tells the 405 error and then redirects me to the success page. :-/

I understand there were a few topics similiar to this, like this for example:

https://answers.netlify.com/t/netlify-form-submissions-now-failing-with-405-method-not-allowed/50396

I tried to replicate this witht his code block:

import React, { useState } from "react";
import { useRouter } from "next/router";
import styles from '../styles/Contact.module.scss'

const ContactForm = ({ contact }) => {
    const [submitterName, setSubmitterName] = useState("");
    const router = useRouter();
    const confirmationScreenVisible =
        router.query?.success && router.query.success === "true";
    const formVisible = !confirmationScreenVisible;

    // Handle the submit event on form submit.
    const handleSubmit = async (event) => {
        event.preventDefault()

        const data = {
            fullName: event.target.fullName.value,
            tel: event.target.tel.value,
            email: event.target.email.value,
            message: event.target.message.value,
        }

        const JSONdata = JSON.stringify(data)
        console.log(JSONdata)

        const response = await fetch('/form.html', {
            method: 'POST',
            body: JSONdata,
            headers: {
                'Content-Type': 'application/json',
            },
        })
        const result = await response.json()
        console.log(result)
    }

    const ConfirmationMessage = (
        <>
            <p>
                Thank you for submitting this form. Someone should get back to you
                within 24-48 hours.
            </p>

            <button
                onClick={() => router.replace("/", undefined, { shallow: true })}
            >
                Submit Another Response
            </button>
        </>
    );

    const theContactForm = (
        <form
            name="contact-form"
            action={handleSubmit}
            method="POST"
            data-netlify="true"
            netlify-honeypot="bot-field"
        >
            <input type="hidden" name="subject" value={`Prospekti ${submitterName} otti yhteyttä Juhokoli.fi`} />
            <input type="hidden" name="contact-form" value="contact-form" />
            <input type="hidden" name="bot-field" />
            <div className={styles.formControl}>
                <label htmlFor="fullName">Nimi *</label>
                <input
                    placeholder="Nimi *"
                    type="text"
                    name="fullName"
                    id="fullName"
                    autoComplete="name"
                    onChange={(e) => setSubmitterName(e.target.value)}
                    required
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="tel">Puhelinnumero *</label>
                <input
                    placeholder="Puhelinnumero *"
                    type="tel"
                    autoComplete="tel"
                    name="tel"
                    id="tel"
                    required
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="email">Sähköposti</label>
                <input
                    placeholder="Sähköposti"
                    type="email"
                    autoComplete="email"
                    name="email"
                    id="email"
                />
            </div>
            <div className={styles.formControl}>
                <label htmlFor="message">Viesti</label>
                <textarea
                    placeholder="Viesti"
                    name="message"
                    id="message"
                />
            </div>
            <div className={styles.formControl}>
                <button
                    type="submit"
                    className="btn">
                    {contact.CTA}
                </button>
            </div>
        </form>
    )


    return (
        <section id={styles.formSection}>
            <div id="yhteydenotto" className={styles.formContainer}>
                {formVisible ? theContactForm : ConfirmationMessage}
            </div>
        </section>
    )
}

export default ContactForm

And this is my html form in Public folder:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Yhteydenottolomake</title>
</head>
<body>
    <form
    name="contact-form"
    data-netlify="true"
    netlify-honeypot="bot-field"
    >
    <input type="hidden" name="contact-form" value="contact-form" />
    <input type="hidden" name="bot-field" />
        <label htmlFor="fullName">Nimi *</label>
        <input
            placeholder="Nimi *"
            type="text"
            name="fullName"
            id="fullName"
            autoComplete="name"
            required
        />
        <label htmlFor="tel">Puhelinnumero *</label>
        <input
            placeholder="Puhelinnumero *"
            type="tel"
            autoComplete="tel"
            name="tel"
            id="tel"
            required
        />
        <label htmlFor="email">Sähköposti</label>
        <input
            placeholder="Sähköposti"
            type="email"
            autoComplete="email"
            name="email"
            id="email"
        />
        <label htmlFor="message">Viesti</label>
        <textarea
            placeholder="Viesti"
            name="message"
            id="message"
        />
</form>
</body>
</html>

But I still got the 405 error with method not allowed.

Could someone tell me what to try next or how to fix my solution with my current attempts?

1

There are 1 best solutions below

1
On

I spent a lot of time on this issue. Because you are using a onSubmit and that is using a POST, you need to remove the method=POST from your form element attributes.