Reputation:
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!
Upvotes: 0
Views: 584
Reputation:
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}`);
Upvotes: 1
Reputation: 119
A couple things you should note for this:
Polka (assuming you're using Polka) does not parse input data by default. You need to use body-parser
or an equivalent package to parse the input body. You can use the example provided here as a base, swapping out the json()
function for the urlencoded()
function.
The fetch()
function takes as its first argument the name of the route file containing your POST
function. If it's stored in contact.json.js
, the equivalent call will be fetch('contact.json', opts)
. Sapper convention is to store all server routes as *.json.js
files.
Upvotes: 1