Http request from javascript business logic?

hey guys,

i need to query an external server from my javascript business logic. I read somewhere that you can do that with HttpURLConnection but I’m really stuck on how to use it, and can’t find any examples. I’ve been trying to adapt various examples online but I’m stuck right now…

Backendless.enablePromises();

Backendless.ServerCode.customEvent(‘testHtml’, request => {

const url = “http://www.google.com”;

const charset = “UTF-8”;

var connection = new URL(url).openConnection();

connection.setRequestProperty(“Accept-Charset”, charset);

var response = new URL(url).openStream();

return {“response”:response};

}

);

When I call ‘testHtml’, the server simply returns [URL is not defined]. So basically, I’m still stuck at the very beginning: I don’t know how to create an url from a string… But even then, I’m really not sure this code would give me the async response I want. So, is there an example somewhere that shows HTML queries? (POST request if possible)

thanks !!

Hi

the URL class you are trying to use looks to be from the Java world. Not from JavaScript and Node.js

You should use Node.js http module to make http requests to external servers.
Alternatively you can use some other thirdparty node modules like request

See also:

thanks Vitaly, I will look into your links, they seem to describe what i’m looking for

Hello Vitaly,
I believe I am getting close, but it’s not working yet. First I have added the external host “www.google.com” and it says that it’s approved.

Then I’m using this code:

‘use strict’;
const http = require(‘http’);
Backendless.enablePromises();

Backendless.ServerCode.customEvent(‘testHtml’, request => {
console.log(http get START);

return new Promise((resolve, reject) => {
console.log(promise START);
http.get(‘http://www.google.com/’, (res) => {
console.log(http get RESPONSE);
let body = ‘’;
res.on(‘data’, (chunk) => body += chunk);
res.on(‘end’, () => {
console.log(http get onEnd);
req.item.apiCallResult = body;
resolve();
});
res.resume();
}).on(‘error’, reject);
});

});

this gives me the following log:

2016-10-17 08:29:16,199 | SERVER_CODE | INFO | http get START
2016-10-17 08:29:16,199 | SERVER_CODE | INFO | promise START
2016-10-17 08:29:21,233 | SERVER_CODE | ERROR | Error: Task execution is aborted due to timeout

so the http GET seems to timeout. am i not handling the response properly or something? ideally i’d like to return something like: return{“reponse”:body}; to the client who sent the “testHtml” query…

thanks!

I suggest you, to do the same in debug mode. So you will have more control of your code, than when everything works correct you, deploy it to server.