使用 node 或 Express 返回 JSON 的正确方法 - Proper way to return JSON using node or Express

问题:

So, one can attempt to fetch the following JSON object:因此,可以尝试获取以下 JSON 对象:

$ curl -i -X GET http://echo.jsontest.com/key/value/anotherKey/anotherValue
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=ISO-8859-1
Date: Wed, 30 Oct 2013 22:19:10 GMT
Server: Google Frontend
Cache-Control: private
Alternate-Protocol: 80:quic,80:quic
Transfer-Encoding: chunked

{
   "anotherKey": "anotherValue",
   "key": "value"
}
$

Is there a way to produce exactly the same body in a response from a server using node or express?有没有办法在使用 node 或 express 的服务器的响应中生成完全相同的正文? Clearly, one can set the headers and indicate that the content-type of the response is going to be "application/json", but then there are different ways to write/send the object.显然,可以设置标题并指示响应的内容类型将是“application/json”,但是有不同的方式来写入/发送对象。 The one that I have seen commonly being used is by using a command of the form:我看到常用的一种是使用以下形式的命令:

response.write(JSON.stringify(anObject));

However, this has two points where one could argue as if they were "problems":然而,这有两点可以争论,就好像它们是“问题”一样:

  • We are sending a string.我们正在发送一个字符串。
  • Moreover, there is no new line character in the end.而且,最后没有换行符。

Another idea is to use the command:另一个想法是使用命令:

response.send(anObject);

This appears to be sending a JSON object based on the output of curl similar to the first example above.这似乎是基于 curl 的输出发送一个 JSON 对象,类似于上面的第一个示例。 However, there is no new line character in the end of the body when curl is again being used on a terminal.但是,当 curl 再次在终端上使用时,正文末尾没有换行符。 So, how can one actually write down something like this with a new line character appended in the end using node or node/express?那么,如何使用 node 或 node/express 在末尾附加一个换行符来实际写下这样的东西呢?


解决方案:

参考一: https://stackoom.com/question/1KdtI
参考二: Proper way to return JSON using node or Express
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章