How To Grab Json File From External Url(places Api) Using Firebase Functions
So, I want to send a request from my app to Firebase using cloud funtions and then process process url and send back JSON file from places api WHAT I HAVE ALREADY DONE/HAVE=> A
Solution 1:
This worked for me., using return before promise returns the result from promise, and we need to use return
when using functions.https.onCall
and res.send
when using functions.https.onRequest
it took me 3 days to get it & no need of adding json=true
in request-promise options when your url returns a json, it just made things complicated
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const rp = require('request-promise');
exports.fetch = functions.https.onCall((req, res) => {
const url = req.url + '&key=MY_API_KEY';
var options = {
uri: url, // Automatically parses the JSON string in the response
};
returnrp(options)
.then(result => {
console.log('here is response: ' + result);
return result;
}).catch(err => {
// API call failed...return err;
});
})
Solution 2:
You should use promises, in your Cloud Function, to handle asynchronous tasks (like the call to the URL). By default request does not return promises, so you need to use an interface wrapper for request, like request-promise.
The following adaptations should do the trick:
const rp = require('request-promise');
exports.fetch = functions.https.onCall((req, res) => {
const url = req.url + '&key=MY_API_KEY';
console.log(url);
var options = {
uri: url,
json: true// Automatically parses the JSON string in the response
};
rp(options)
.then(response => {
console.log('Get response: ' + response.statusCode);
res.send(response);
})
.catch(err => {
// API call failed...
res.status(500).send('Error': err);
});
})
Post a Comment for "How To Grab Json File From External Url(places Api) Using Firebase Functions"