• V
 

包含在另一个流中捕获的数据

问题

您希望使用另一个流捕获的数据来响应 HTTP 请求。

解决方案

使用 流上下文 存储数据,以便可以在 HTTP 流中检索。

示例

[{"id":"92eaf6c0.6d1508","type":"inject","z":"3045204d.cfbae","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"x":100,"y":480,"wires":[["8055b557.7faa48"]]},{"id":"8055b557.7faa48","type":"change","z":"3045204d.cfbae","name":"Store time","rules":[{"t":"set","p":"timestamp","pt":"flow","to":"payload","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":270,"y":480,"wires":[[]]},{"id":"93bf2335.6c40e","type":"http in","z":"3045204d.cfbae","name":"","url":"/hello-data","method":"get","swaggerDoc":"","x":120,"y":520,"wires":[["9e3aa25e.61c56"]]},{"id":"9e3aa25e.61c56","type":"change","z":"3045204d.cfbae","name":"Copy time","rules":[{"t":"set","p":"timestamp","pt":"msg","to":"timestamp","tot":"flow"}],"action":"","property":"","from":"","to":"","reg":false,"x":310,"y":520,"wires":[["f2c385a.f0d3c78"]]},{"id":"f2c385a.f0d3c78","type":"template","z":"3045204d.cfbae","name":"page","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"<html>\n    <head></head>\n    <body>\n        <h1>Time: {{ timestamp }}</h1>\n    </body>\n</html>","x":470,"y":520,"wires":[["def756a1.2108a8"]]},{"id":"def756a1.2108a8","type":"http response","z":"3045204d.cfbae","name":"","x":610,"y":520,"wires":[]}]
[~]$ curl https://:1880/hello-data
<html>
    <head></head>
    <body>
        <h1>Time: 1480201022517</h1>
    </body>
</html>

讨论

在流中存储和检索数据有许多不同的方法。例如,使用外部数据库。

Node-RED 提供 流上下文 作为简单的键/值存储,可供同一选项卡上的所有节点访问。

上面的示例使用 Change 节点将 Inject 节点生成的时间戳存储到 流上下文 中。然后,处理 HTTP 请求的流使用另一个 Change 节点检索该值,将其附加到消息中,然后将消息传递给 Template 节点以生成响应。