简体   繁体   English

Svelte/Sapper:POST 上的身体是空的

[英]Svelte/Sapper: Body empty on POST

I'm trying to create a login form using sapper, but am encountering the following problem when trying to test a basic POST fetch.我正在尝试使用 sapper 创建登录表单,但在尝试测试基本 POST 获取时遇到以下问题。

In routes/login/login.svelte , I have the following code which is called on a button click:routes/login/login.svelte中,我有以下代码,它在单击按钮时被调用:

<script>
  let data = {"email":"test"};

  const handleLogin = async () => {
    const response = await fetch("/login/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: data
    });
  };
</script>

Which should send what is in data to routes/login/login.js which has the following code:哪个应该将data中的内容发送到具有以下代码的routes/login/login.js

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

My problem is that this only returns {} rather than the data sent in the svelte page.我的问题是这只返回{}而不是在苗条页面中发送的数据。 Any ideas as to why this is happening and where I'm going wrong?关于为什么会发生这种情况以及我哪里出错的任何想法? Thanks.谢谢。

When sending the data, you should also stringify it there发送数据时,您还应该在那里对其进行字符串化

   body: JSON.stringify(data)

as an extra make sure you have body-parser installed and added as middleware in the server, this package will help you handle requests that have send json data in their body.作为额外的确保您已安装正文解析器并将其作为中间件添加到服务器中,此 package 将帮助您处理已在其正文中发送 json 数据的请求。

polka() // You can also use Express
    .use(
        compression({ threshold: 0 }),
        sirv('static', { dev }),
        bodyparser(),
        sapper.middleware()
    )
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });

Building on the previous answer, I'm writing here the full working solution.基于先前的答案,我在这里写下完整的工作解决方案。 Your problems may be due to:您的问题可能是由于:

  1. Not using the json parse middleware不使用json解析中间件
  2. Not treating fetch as a promise不将fetch视为 promise

Here's how I'd fix it:这是我要解决的方法:

  1. npm i body-parser
  2. Add the json middleware in your server.jsserver.js中添加json中间件
const { json } = require('body-parser');

polka()
    .use(
      compression({ threshold: 0 }),
      json(),
      sirv('static', { dev }),
      sapper.middleware()
    )
    .listen(PORT, err => {
        if (err) console.log('error', err);
    });
  1. Treat the fetch response as a Promise.fetch响应视为 Promise。 This is how your Svelte component should look like (notice the chained then ):这就是您的 Svelte 组件的外观(注意链接的then ):
<script>
  let data = {"email":"test"};

  const handleLogin = async () => {
    await fetch(`your-endpoint`, {
      method: 'POST',
      body: JSON.stringify(data),
      headers:{
        'Content-Type': 'application/json'
      }
    })
    .then(res => res.json())
    .then(res => console.log(res)); // {email: "test"}

  };
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM