svelte / sapper-服务器外部的任何提取请求上的404

问题描述

使用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();
}

同样,在我的路线中,我使用导出POST功能添加了js文件

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文件中进行实际发布,但没有进行任何操作。互联网上似乎没有其他人与这个问题有关,请帮忙!谢谢!

解决方法

您应该注意以下几点:

  1. Polka(假设您使用的是Polka)默认情况下不会解析输入数据。您需要使用body-parser或等效包来解析输入正文。您可以使用提供的示例here作为基础,将json()函数换成urlencoded()函数。

  2. 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}`);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...