【问题标题】:Svelte/Sapper: Body empty on POSTSvelte/Sapper:POST 上的身体是空的
【发布时间】:2020-07-16 14:09:45
【问题描述】:

我正在尝试使用 sapper 创建登录表单,但在尝试测试基本 POST 提取时遇到以下问题。

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>

应该将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));
}

我的问题是这只返回{} 而不是在苗条页面中发送的数据。关于为什么会发生这种情况以及我哪里出错的任何想法?谢谢。

【问题讨论】:

    标签: javascript node.js fetch svelte sapper


    【解决方案1】:

    发送数据时,你也应该在那里进行字符串化

       body: JSON.stringify(data)
    

    另外,请确保您已安装 body-parser 并将其作为中间件添加到服务器中,此软件包将帮助您处理在其正文中发送 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);
        });
    

    【讨论】:

    • 感谢您的回复,我添加了JSON.stringify 位并从bodyparser 导入了json,但由于某种原因仍然收到空白返回
    • 不是bodyparser(),而是bodyParser.json()
    • 代码中的 response 对象将不包含返回的实际 json 数据,因为您必须这样做 response.json() 返回一个承诺。您可以通过 fetch(...).then(res =&gt; res.json()) 直接获取 json 数据作为响应。 (这假设服务器没有返回任何错误)
    【解决方案2】:

    在上一个答案的基础上,我在这里写下完整的工作解决方案。您的问题可能是由于:

    1. 不使用json解析中间件
    2. 不将fetch 视为承诺

    这是我的解决方法:

    1. npm i body-parser
    2. server.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. fetch 响应视为承诺。这就是您的 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-26
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 2021-09-20
      • 2013-07-11
      • 2016-07-21
      • 1970-01-01
      相关资源
      最近更新 更多