HTTP Request

Discussions about Z-Way software and Z-Wave technology in general
Post Reply
enco.josh
Posts: 35
Joined: 10 Mar 2014 22:10

HTTP Request

Post by enco.josh »

I am having some issues sending data to a webserver using the http.request function. I am binding to events and then sending a JSON object consisting of a few indentifying properties and the this object from the call back.

Code: Select all

sendEvent({id: id, event: this}, httpSucess, httpError, httpComplete);

function sendEvent(jsonData, successCb, errorCb, completeCb) {
	console.log("HTTP Post - " + JSON.stringify(jsonData));
	http.request({
		method: 'POST',
		url: "[insert url here]",
		header: {
			"Content-Type": "application/json"
		},
		contentType: "application/json",
		data: jsonData,
		async: true,
		success: successCb,
		error: errorCb,
		complete: completeCb
	});
}

1. If I send the object as is, the "this" object is turned into a string as [object DataHoldObj] (or something similar). The actual JSON object is not sent. I have worked around this by using {id: id, event: JSON.stringify(this)} instead. I then parse the JSON event on the server side. I think this happens because the post is sent via url encoded parameters. Is there a way to post raw data?

2. The server receives the Content-Type parameter in the header as application%2Fjson. I know this is because it is being URL encoded, but I don't think the headers need to be encoded. Correct?
User avatar
PoltoS
Posts: 7579
Joined: 26 Jan 2011 19:36

Re: HTTP Request

Post by PoltoS »

1. Indeed, data is finally a string object and a .toString() function is called just before evaluating the object. You need to convert it to a JSON string first, since JSON.stringify is not same as toString for most objects in JS:

> var a = {}
> a.x = 2
Object {x: 2}
> a.toString()
"[object Object]"
> JSON.stringify(a)
"{"x":2}"

2. certainly a bug - we have created an issue: https://github.com/Z-Wave-Me/z-way-issues/issues/4
Post Reply