Facing Issue while calling external URL (google geocoding URL)

Hi,
I am facing this error while calling google API to get a geo location address.
{
“code”: 0,
“message”: “Protocol “https:” not supported. Expected “http:””,
“errorData”: {}
}

Code is below, Please check
const address =‘37716-4019’
var url = “https://maps.googleapis.com/maps/api/geocode/json?&address="+address+"&key=Google GeoCoding API Key”; //client’s Key
const http = require(‘http’);
return http.get(url)
.success(function(data) {
return data;
})
Backendless Not allow Https request calls while google is also accepting only HTTPS requests :frowning:
What do we do now Please help

Hello, @Ayaz_Khan.

You should try replacing this line of code:
const http = require(‘http’);
to this:
const https = require(‘https’);

Best Regards, Nikita.

Hi @Nikita_Fedorishchev ,

Thanks for your reply,
HTTPS related issue has been resolved But
when I run this URL from browser’s tab I got this response
response
{
“results” : [
{
“address_components” : [
{
“long_name” : “37716”,
“short_name” : “37716”,
“types” : [ “postal_code” ]
},

],
“formatted_address” : “Clinton, TN 37716, USA”,
“geometry” : {
“bounds” : {
“northeast” : {
“lat” : 36.2053809,
“lng” : -84.03294509999999
},

},
“location” : {
“lat” : 36.0995654,
“lng” : -84.16461629999999
},
“location_type” : “APPROXIMATE”,
“viewport” : {
“northeast” : {
“lat” : 36.2053809,
“lng” : -84.03294509999999
},

}
},
“partial_match” : true,
“place_id” : “ChIJi5VC3ds1XIgRxR93Jxz9AuY”,
“types” : [ “postal_code” ]
}
],
“status” : “OK”
}

But When I run API in backendless for the same URL I got this
response {
{
“outputData”: [
{
“data”: “GET /maps/api/geocode/json?&address=37716-4019&key=AIzaSyCHu7TLwnT-R21Gd2SCwB4rHGaQWJhIdq8 HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n”,
“encoding”: “latin1”
}
],
“_eventsCount”: 1,
“agent”: {
“_eventsCount”: 2,

        "sockets": {
            "maps.googleapis.com:443:::::::::::::::::::::": [
                {
                    "_eventsCount": 9,
                    "ssl": {
                        "_parent": {
                            "reading": false,
                            "onconnection": null
                        },
                        ...
                    },
                    "_events": {
                        "end": [
                            null,
                            null
                        ],
                        "close": [
                            null,
                            null,
                            null
                        ]
                    },
                    "_rejectUnauthorized": true,
                    ...
                    "alpnProtocol": null,
                    "_writableState": {
                        "bufferedIndex": 0,
                        ...
                    },
                    "_requestCert": true,
                    "_tlsOptions": {
                        "rejectUnauthorized": true,
                    },
                    "_host": "maps.googleapis.com",
                    "authorizationError": null,
                    "encrypted": true,
                    "_SNICallback": null,
                    "servername": null,
                    "_securePending": false,
                    "_readableState": {
                        "emitClose": false,
                        ...
                        "buffer": {
                            "head": null,
                            ...
                        },
                        "highWaterMark": 16384,
                        ...
                    },
                    "connecting": true
                }
            ]
        },
        "maxTotalSockets": null
    },
    "sendDate": false,
    "aborted": false,
    "_trailer": "",
    "_header": "GET /maps/api/geocode/json?&address=37716-4019&key=AIzaSyCHu7TLwnT-R21Gd2SCwB4rHGaQWJhIdq8 HTTP/1.1\r\nHost: maps.googleapis.com\r\nConnection: close\r\n\r\n",
    "_defaultKeepAlive": true,
    "_removedConnection": false,
    "_events": {},
    "writable": true,
    "_removedContLen": false,
    "_hasBody": true,
    "path": "/maps/api/geocode/json?&address=37716-4019&key=AIzaSyCHu7TLwnT-R21Gd2SCwB4rHGaQWJhIdq8",
    "protocol": "https:",
    "_contentLength": 0,
    "reusedSocket": false,
    "_last": true,
    "_headerSent": true,
    "host": "maps.googleapis.com",
    "shouldKeepAlive": false,
    "res": null,
    "_removedTE": false,
    "useChunkedEncodingByDefault": false,
    "method": "GET",
    "_ended": false,
    "upgradeOrConnect": false,
    "finished": true,
    "chunkedEncoding": false,
    "outputSize": 149,
    "timeoutCb": null,
    "destroyed": false,
    "maxHeadersCount": null,
    "parser": null,
    "socket": null,
    "_keepAliveTimeout": 0
}

}

Hello @Ayaz_Khan,

I’m not sure you’re using the https module correctly, please see the docs here:
https://nodejs.org/api/https.html

Here how your method should look like:

async getAddressData() {
    // `res` is an instance of Node's built-in `ServerResponse` class:
    // https://nodejs.org/api/http.html#http_class_http_serverresponse
    const res = await new Promise(resolve => {
      https.get(URL, resolve);
    });
    
    // A ServerResponse is a readable stream, so you need to use the
    // stream-to-promise pattern to use it with async/await.
    const data = await new Promise((resolve, reject) => {
      let data = '';
      res.on('data', chunk => data += chunk);
      res.on('error', err => reject(err));
      res.on('end', () => resolve(data));
    });
    
    return JSON.parse(data);
}

But I would suggest you not use this module since Backendless offers a more suitable way to fetch data. Try the following way:

getAddressData() {
   return Backendless.Request.get(URL)
}

Regards,
Stanislaw

Hello @stanislaw.grin,
Thanks For your Help, My issue Has been resolved. :slight_smile:

Hi @stanislaw.grin,

When I simply run code it gives me desired result
But When I try to run it in a loop it gives this result

[
    {
        "path": "https://maps.googleapis.com/maps/api/geocode/json?&address='37705-0000'&key=**GeoCoding API KEY**",
        "headers": {},
        "cacheTTL": 0,
        "method": "get",
        "queryParams": {},
        "encoding": "utf8",
        "events": {},
        "unwrap": true
    },
    {
        "path": "https://maps.googleapis.com/maps/api/geocode/json?&address='37924-3879'&key=**GeoCoding API KEY**",
        "headers": {},
        "cacheTTL": 0,
        "method": "get",
        "queryParams": {},
        "encoding": "utf8",
        "events": {},
        "unwrap": true
    }
]

I want to update lat long of multiple addressess which is stored in my database.
Please help

Please show how do you run it in a loop.
You should use Promise.all in order to wait for each request. Is your code looks something like the following?

getAddressData() {
  return Promise.all(yourArray.map(data => {
    return Backendless.Request.get(URL) // I don't know what data in your list
  }))
}

Here is my code Please see

 let charity = {};
    await Promise.all(
        charity = charityData.map(function( data ) {
              let address = data.zipCode
              let url = "https://maps.googleapis.com/maps/api/geocode/json?&address="+`'${address}'`+"&key=***Google geocoding Key***"; //client's Key
              let urlResponse = Backendless.Request.get(url)    
               // let latitude = urlResponse.results[0].geometry.location.lat;
               // let longitude = urlResponse.results[0].geometry.location.lng;
              //let updateCharitiesData = {'objectId': data.objectId, 'latitude':latitude, 'longitude':longitude};
              return urlResponse;
        })
      );
    return charity;

Hello @Ayaz_Khan

You are using the JS object/class “Promise” incorrectly.
We provide support for our product, not the correct writing of JavaScript code.
I advise you to look for how to use the object “Promise” correctly in guides or consult resources such as StackOverflow

Regards,
Viktor

Hi Backendless Team,

I have been struggling many hours now with a similar issue for fetching external API data.
Once I found the method Backendless.Request.get(URL) in this answer, it solved my problem.
I have not found any documentation for this or similar functions.
Is there some documentation available for this and similar functions?

Hello @Didrik_Hoglund

Documentation for Backendless.Request you can find by the following link GitHub - Backendless/Request: Simple Node.js and browser REST client.