我需要对 JSON 对象进行一些说明。在我的节点后端,我收到一个 JSON 对象,在我完成我需要的键/值对之后,我将它发送到前端。这就是我感到困惑的地方 - 我仍然需要通过 response.json() 将该响应对象转换为 json。为什么?如果后端正在传递 JSON,那么为什么我需要将响应 obj 转换为 JSON?// test.js (node)const testObj = { "test1": { "1": "Hello there" }}app.get('some-route', async(req,res) =>{ res.send(testObj)}// front.js (React)async someFunc(){ const response = await fetch('/some-route'); const data = await response.json(); //why?}
3 回答
幕布斯7119047
TA贡献1794条经验 获得超8个赞
响应对象不仅仅是它的 JSON 部分。它包含所有 HTTP 协议元素,如headers、响应状态等。
当您使用时,res.json()
您是在告诉您的代码仅将 JSON 部分与所有其他内容分开。
要更多地了解 HTTP 响应,我建议您阅读此。
墨色风雨
TA贡献1853条经验 获得超6个赞
响应对象不是您从后端发送的任何内容,它将是一个Response 对象。这就是 Fetch API 的工作原理。该 Response 对象将包含大量元数据和一些方法,包括.jsonwhich Takes a Response stream and reads it to completion. It returns a promise that resolves with the result of parsing the body text as JSON。
如果不想经历这两个步骤,直接写这个函数就行了。
const fetchJson = async url => {
const response = await fetch(url)
return response.json()
}
并像这样使用它:
async someFunc(){
const data = await fetchJson('/some-route')
}
添加回答
举报
0/150
提交
取消