HTTP POST in node-red js

2020-06-22 05:39发布

问题:

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.

回答1:

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).



回答2:

From your subsequent question on this topic, I see you've got past the issues you were having here.

To repeat the answer I gave there, the payload you want to post should be in a property called 'payload' on the object you return from the function. The documentation of the http request node describes all of that.

You will find there is not currently a lot of activity on node-red within stack overflow. Hopefully that will change over time, but for now you'll find the mailing list is much more responsive.

Also, if you have specific feedback, we'd welcome it on the mailing list.