• V
 

提供 JSON 内容

问题

你想通过 JSON 数据响应一个 HTTP 请求。

解决方案

使用 msg.headers 对象将响应的 content-type 设置为 application/json

示例

[{"id":"c8107088.37ef9","type":"http in","z":"3045204d.cfbae","name":"","url":"/hello-json","method":"get","swaggerDoc":"","x":120,"y":620,"wires":[["4e8237da.b17dc8"]]},{"id":"4e8237da.b17dc8","type":"template","z":"3045204d.cfbae","name":"页面","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{ \"Hello\": \"World\" }","x":290,"y":620,"wires":[["65401623.9abfe8"]]},{"id":"65401623.9abfe8","type":"change","z":"3045204d.cfbae","name":"设置头部","rules":[{"t":"set","p":"headers","pt":"msg","to":"{}","tot":"json"},{"t":"set","p":"headers.content-type","pt":"msg","to":"application/json","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":450,"y":620,"wires":[["f7d3e35a.082c2"]]},{"id":"f7d3e35a.082c2","type":"http response","z":"3045204d.cfbae","name":"","x":610,"y":620,"wires":[]}]
[~]$ curl -i http://localhost:1880/hello-json
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 20
ETag: W/"14-jgfjeX8FTECC4q5nXp6n5g"
Date: Sat, 26 Nov 2016 23:07:50 GMT
Connection: keep-alive

{ "Hello": "World" }

讨论

可以使用 msg.headers 属性设置响应中返回的 HTTP 头部。它应该是一个包含每个头部键值对的对象。

为了返回格式良好的 JSON,Content-Type 头部应该设置为 application/json,以便接收方知道将其作为 JSON 数据处理。