繁体   English   中英

解析来自 Fetch api 和 JSON 的数据时遇到问题

[英]Trouble parsing data from Fetch api and JSON

节日快乐!

我在 NEXT/React 页面中有以下功能:

async function onSubmit(values) {
    try {
      console.log(values);
      console.log(`JSON: ${JSON.stringify(values)}`);
      await postData("/api/put", values);
    } catch (error) {
      console.error(error);
    }

    async function postData(url = "", data = {}) {
      const response = await fetch(url, {
        method: "POST",
        mode: "cors",
        cache: "no-cache",
        credentials: "same-origin",
        headers: {
          "Content-Type": "application/json",
          "Content-Type": "application/x-www-form-urlencoded"
        },
        redirect: "follow",
        referrer: "no-referrer",
        body: JSON.stringify(data)
      });
      return await response.json(); // parses JSON response into native JavaScript objects
    }
  }

第二个console.log()给了我以下内容:

JSON: {"name":"Tim","email":"bob@bob.com","title":"grwewdfgherwfsdhtrdfsgh","body":"gfggfdsbngfdsbfnggdffbffgds"}

对我来说看起来很棒,让我相信body: JSON.stringify(data)会产生相同的结果; 在我的后端,我的request.body是:

body:
   [Object: null prototype] {
     '{"name":"Tim","email":"bob@bob.com","title":"fdsfsdfsdfsdf","body":"ytgfhjtrghrtesdrew"}': '' } }

当我尝试做const data = JSON.parse(req.body); 我收到以下错误:

(node:21676) UnhandledPromiseRejectionWarning: TypeError: Cannot convert object to primitive value
    at JSON.parse (<anonymous>)

有人可以帮我吗?

你不是已经在使用 await 来获得响应了吗? 你可以尝试返回 response.json() 而不是 return await response.json() 吗?

我这么认为的原因是当语句在承诺中解决时应该使用 await 。 response.json() 没有。

暂无
暂无

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

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