使用 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章