How to set data in response object data? SOLVED!

I’m working on a project where I want to send analog values to a third party server. With httpresponse.headers and httpresponse.send I’m able to have my agent send a JSON containing my data to my node server, however it’s not in the format I would like. The object my server gets looks like this:

{ statusCode: 200, content: 'OK', headers: { date: 'Thu, 17 Jul 2014 02:10:59 GMT', server: 'nginx/1.4.2', voltage: '0', 'x-frame-options': 'SAMEORIGIN', 'x-imp-requestid': 'w7fJCoT+Mp9IvGx7MC4d6A', 'content-length': '2', connection: 'keep-alive' }, data: null }

The problem is that I don’t know how to place my data ‘voltage’ within the data object. As you can see httpresponse.headersI can place it within headers, as well as, httpresponse.send within content.

Thanks in advance for any help :slight_smile:

I believe data is the body of the body of the text. You would want to do two things:

  1. Add a “content-type: application/json” header:
  2. Create an object with a voltage field, and json encode it:

`local data = http.jsonencode({ “voltage”: voltage });
local headers = { “content-type”: “application/json” };

http.post(url, headers, data).sendasync(function(resp) {
server.log(resp.statuscode + ": " + resp.body);
});`

Thanks @beardedinventer! I got very frustrated with this project so I took a break but I just got back to it and your post definitely got me in the right direction!

All I had to do was add { “content-type”: “application/json” }; to my header and all was well :slight_smile:

response.header("content-type", "application/json");

Excellent - glad you could get it working :slight_smile:

Many servers ignore the “content-type” header, but many require it - it’s generally a good idea to include… and probably something we should include in some more of our documentation