Node-RED

Node-REDを使って、JSONデータをPOSTで送る方法

Node-REDを使って、JSONデータをPOSTで送る方法がわかったのでそれのメモ。

フロー

Node RED 2021 09 10 21 30 25

このフローは、実行のInjectノードをクリックすると、functionノード(Request Headers)で用意したjsonデータをlocalhost:1880/hello-formにPOSTにおくります。

[{"id":"5b98a8ac.a46758","type":"http in","z":"f4d18839.442cc8","name":"","url":"/hello-form","method":"post","upload":false,"swaggerDoc":"","x":640,"y":80,"wires":[["8eabd308.4c855","fe4e531b.95f61"]]},{"id":"6dc8d23.285182c","type":"http request","z":"f4d18839.442cc8","name":"","method":"POST","ret":"obj","paytoqs":"body","url":"http://localhost:1880/hello-form","tls":"","persist":false,"proxy":"","authType":"","x":890,"y":340,"wires":[["47f301d3.2508"]]},{"id":"e16244b9.c94a58","type":"function","z":"f4d18839.442cc8","name":"Request Headers","func":"var a = {\"name\": \"taro\", \"age\": 23, \"sex\": \"man\"};\nvar b = {\"name\": \"ken\", \"age\": 11, \"sex\": \"man\"};\n\nmsg.headers = {};\nmsg.headers['content-type'] = 'application/json';\n\nmsg.payload = { a,b };\n\nreturn msg;\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":810,"y":280,"wires":[["6dc8d23.285182c"]]},{"id":"adb52c94.6978a","type":"inject","z":"f4d18839.442cc8","name":"実行","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":690,"y":220,"wires":[["e16244b9.c94a58"]]},{"id":"8eabd308.4c855","type":"debug","z":"f4d18839.442cc8","name":"response","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":860,"y":60,"wires":[]},{"id":"47f301d3.2508","type":"debug","z":"f4d18839.442cc8","name":"response","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":980,"y":400,"wires":[]},{"id":"fe4e531b.95f61","type":"http response","z":"f4d18839.442cc8","name":"HTTP response","statusCode":"200","headers":{},"x":880,"y":120,"wires":[]}]

フローの解説

Node RED 2021 09 10 21 31 23

Jsonデータは下記をmsg.payloadに設定。

var a = {"name": "taro", "age": 23, "sex": "man"};
var b = {"name": "ken", "age": 11, "sex": "man"};

HTTP RequestのHeaderには、msg.headersに必要な項目を記載して、次のhttp requestに送ります。

また、http responseには設定し、status codeで400を返します。

まとめ

これでやりたいことはかなりできそう。

ABOUT ME
中畑 隆拓
スマートライト㈱ 代表取締役。IoTソリューションの開発、スマートホーム&オフィスのコンサルティング、DALI,KNX,EnOceanなどのインテグレーションを行っています。

COMMENT

メールアドレスが公開されることはありません。 が付いている欄は必須項目です