无法解析来自 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 来获取响应了吗?您可以尝试 return response.json() 而不是 return await response.json() 吗?
我这么认为的原因是当声明在承诺中解析时应该使用 await 。 response.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 来获取响应了吗?您可以尝试 return response.json() 而不是 return await response.json() 吗?
我这么认为的原因是当声明在承诺中解析时应该使用 await 。 response.json() 没有。