HTTP POST in node-red js

ninja.stop picture ninja.stop · Aug 26, 2014 · Viewed 13k times · Source

I want to know how to do a http POST request with a JSON data into some server with API key. I searched in http://nodered.org/docs/ But they haven't written anything clearly. The documentation is very messy and not even good to understand. However, I have tried to POST a JSON data which is stringified:

{"version":"1.0.1","sensors":[{"sensor":"accel","output":[{"name":"accelert","type":"dcmotion"}]}]}

I have written the API in function node as (API is arbitary here, not original)

var msg = {"version":"1.0.1","sensors":[{"sensor":"accel","output":[{"name":"accelert","type":"dcmotion"}]}]}

msg.headers: {
                    'x-api-key': 'ucasdfeacceacxfAIH2L4=',
                    'content-type': 'application/json"
                }

I got this example from here : https://groups.google.com/forum/#!msg/node-red/nl9Be0dN55g/S_VYMTjOanEJ

And I added input node as HTTP POST then given the url and connected it with function added one debug node. Now I deployed it. I am getting error : Unexpected token in API node

Now I'm not sure how to do that. I am not getting how to do this. Please help me out. No tutorial available in node red site.

Answer

kmarabet picture kmarabet · Dec 18, 2014

Instead of var msg = {... you should use msg.payload = {... .

Because msg is a standard JSON object message passed between node-red nodes, so should not be declared using var, and its payload property contains the body of the message, so when the msg is provided for the HTTP request node the payload property is sent as the body of the request (see the info tab of the HTTP request node).