Warm tip: This article is reproduced from serverfault.com, please click

svelte/sapper

发布于 2020-11-10 13:17:22

Using the sapper template, I deployed my app on netlify. I want to integrate netlify forms with sapper, so I used the docs form structure.

<form name="contact" method="POST" data-netlify="true">
    <p>
        <label>Name<input type="text" bind:value={$user.name} /></label>
    </p>
    <p>
        <label>E-mail<input type="text" bind:value={$user.email} /></label>
    </p>
    <p>
        <label>Telephone<input type="text" bind:value={$user.phone} /></label>
    </p>
    <input type="hidden" name="form-name" value="contact" />

    <button on:submit|preventDefault={submitForm} type="submit">Reach out</button>
</form>

With just this, the form is sent to netlify on submit, but it is empty. So taking the example in the docs I try to create my own fetch post request

let submitForm =(event)=>{
let formdata = new FormData();
formdata.append('name',$user.name);
formdata.append('email',$user.email);
formdata.append('telephone',$user.telephone);
    fetch("/contact/", {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: formdata,
  })
    .then(() => alert("Success!"))
    .catch(error => alert(error));

  event.preventDefault();
}

As well, inside of my routes, I add the js file with the export POST function.

export async function post(req, res, next) {
    /* Initializes */
    res.setHeader('Content-Type', 'application/json')
    /* Retrieves the data */
    var data = req.body
    /* Returns the result */
    return res.end(JSON.stringify(data))
  }

No matter what I do, I always get a 404 instantly when I try to submit the form. I've tried different URLs in the fetch, I've tried doing the actual post in the js file, nothing. There seems to be nobody else on the internet with this issue on sapper, please help! Thank you!

Questioner
user9844377
Viewed
0
user9844377 2020-11-30 10:37:47

The issue was that the values weren't wrapped in quotes. I just cast them using es6 backdash syntax and it worked!

formdata.append('name',`${user.name}`);
formdata.append('email',`${user.email}`);
formdata.append('telephone',`${user.telephone}`);