从后端向前端发送JSON [英] Sending JSON from backend to frontend

查看:914
本文介绍了从后端向前端发送JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对JSON对象进行一些说明.在节点后端内部,我收到一个JSON对象,完成所需的键/值对后,将其发送到前端.这就是我感到困惑的地方-我仍然需要通过response.json()将响应对象转换为json.为什么?如果后端正在传递JSON,那么为什么我需要将响应obj转换为JSON?

I need some clarification on JSON objects. Inside my node backend, I receive a JSON object and after I'm done going through which key/value pairs I need, I send it off to the frontend. This is where I'm getting confused- I still need to turn that response object into json via response.json(). Why? If the backend is passing JSON, then why would I need to turn the response obj into 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?
}

推荐答案

由于在您的前端,fetch API会接收一个缓冲区-字节数组,其中可以包含任何有效载荷.它可以是图像,纯文本,文件或JSON负载.

Because on your front-end, the fetch API receives a buffer -- an array of bytes, which could contain any payload. It could be an image, plain text, a file, or a JSON payload.

知道后端将要发送的内容后,您需要接收数据的缓冲区,然后对它执行.json() API,本质上是要求将缓冲区解释为表示JSON对象的序列化字符串,然后让Javascript引擎将该字符串评估(反序列化)为对象.

Knowing what your back-end is going to send down, you need to receive the buffer of the data and then perform the .json() API on it, essentially asking that the buffer be interpreted as a serialized string representing a JSON object, and then having the Javascript engine evaluate (deserialize) that string into an object.

Fetch是一个多功能API,对于服务器要发送的有效负载没有任何先验知识.您正在指示它使用.json()函数将有效载荷视为JSON.

Fetch is a multi-purpose API that doesn't have any prior knowledge about the payload that the server is going to send. You are instructing it to treat the payload as JSON by using the .json() function.

除了.json()之外,还有其他辅助方法可以读取和解析各种其他可能的响应类型;例如:例如,.text()表示纯文本,.formData()表示形式编码的数据(类似于查询字符串值),.blob().arrayBuffer()表示对返回的数据的字节级访问.您将根据API期望的响应类型使用适当的方法.

Besides .json(), there are other helper methods to read and parse a variety of other possible response types; for example, .text() for plain text, .formData() for form encoded data (similar to querystring values), .blob(), and .arrayBuffer() for byte-level access to the returned data. You will use the appropriate method based on the response type that you're expecting from the API.

https://developer.mozilla.org/zh-CN /docs/Web/API/Fetch_API

这篇关于从后端向前端发送JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆