简体   繁体   English

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

[英]Trouble parsing data from Fetch api and JSON

Happy Holidays!节日快乐!

I have the following function in a NEXT/React page:我在 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
    }
  }

The second console.log() gives me the the following:第二个console.log()给了我以下内容:

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

Looks great to me and leads me to believe the body: JSON.stringify(data) would yeild the same result, however;对我来说看起来很棒,让我相信body: JSON.stringify(data)会产生相同的结果; on my back-end, my request.body is:在我的后端,我的request.body是:

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

When I try to do const data = JSON.parse(req.body);当我尝试做const data = JSON.parse(req.body); i get the following error:我收到以下错误:

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

Can someone please help me out?有人可以帮我吗?

aren't you already using await to get the response?你不是已经在使用 await 来获得响应了吗? could you try to return response.json() instead of return await response.json()?你可以尝试返回 response.json() 而不是 return await response.json() 吗?

The reason I think so is that await should be used when the statement resolves in a promise.我这么认为的原因是当语句在承诺中解决时应该使用 await 。 response.json() does not. response.json() 没有。

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

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