Page 1 of 1

Correct way of processing an http.request response

Posted: 26 Mar 2015 12:40
by elvizgz
Hello!
I'm writting a module that makes a call to an URL using http.request method. I need to process the result of the request but I'm not sure the right way to do it. I've tried this:

Code: Select all

http.request({
                method: 'GET',
                url: encodeURI(myURL),
                success: function (response) {
                    console.log("Success!");
                },
                error: function () {
                    console.log("ERROR!!");
                }
           });
but I'm not getting any log (nor success, nor error). I've also tried with a callback function:

Code: Select all

http.request({
                method: 'GET',
                url: encodeURI(myURL),
                }, function (response) {
console.log("Callback!");
});
But it's not working either. Finally, I tried this:

Code: Select all

var response = http.request({
                method: 'GET',
                url: encodeURI(myURL),
           });
console.log(JSON.stringify(response));
And it's the way I'm getting something. Is this the correct way of doing it? It looks strange for me not be able to execute a callback function.

Re: Correct way of processing an http.request response

Posted: 26 Mar 2015 12:52
by pz1
Look into the OpenWeather module to see an example

Re: Correct way of processing an http.request response

Posted: 26 Mar 2015 15:38
by elvizgz
Thanks pz1!

I've already tried that:

Code: Select all

http.request({
                method: 'GET',
                url: encodeURI(myURL),
                success: function (response) {
                    console.log("Success!");
                },
                error: function () {
                    console.log("ERROR!!");
                }
           });
I couldn't see the console.log output in z-way-server.log so I thought it wasn't working. I think the reason was because I didn't specify async:true. Could be?

Re: Correct way of processing an http.request response

Posted: 26 Mar 2015 15:42
by pz1
Could quite wel be. My PVLogger (see Recipes) code has this

Code: Select all

	http.request({
		url : "http://" + self.config.pvlogger + "/status.xml",
		method : "GET",
		async : true,
		success : function (response) {

Re: Correct way of processing an http.request response

Posted: 26 Mar 2015 15:57
by elvizgz
Ok. Thanks for your help!