问题描述
使用sapper模板,我在netlify上部署了我的应用程序。我想将netlify表单与sapper集成在一起,所以我使用了docs表单结构。
<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>
仅此,表单就在提交时发送到netlify,但它为空。因此,以文档中的示例为例,我尝试创建自己的提取请求
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();
}
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))
}
无论我做什么,当我尝试提交表单时,我总是立即得到404。我尝试在提取中使用不同的URL,我尝试在js文件中进行实际发布,但没有进行任何操作。互联网上似乎没有其他人与这个问题有关,请帮忙!谢谢!
解决方法
您应该注意以下几点:
-
Polka(假设您使用的是Polka)默认情况下不会解析输入数据。您需要使用
body-parser
或等效包来解析输入正文。您可以使用提供的示例here作为基础,将json()
函数换成urlencoded()
函数。 -
fetch()
函数将包含您的POST
函数的路由文件的名称作为第一个参数。如果存储在contact.json.js
中,则等效调用将为fetch('contact.json',opts)
。分配器惯例是将所有服务器路由存储为*.json.js
文件。
问题在于这些值没有用引号引起来。我只是使用es6 backdash语法对它们进行了转换,并且有效!
formdata.append('name',`${user.name}`);
formdata.append('email',`${user.email}`);
formdata.append('telephone',`${user.telephone}`);