I'm trying to call an external POST API from my firebase function but it's not working as expected. I'm calling the firebase function from my android app. Following are the code snippets for my function, android call and the error that I'm getting in firebase console:
Firebase Function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const https = require('https');
admin.initializeApp(functions.config().firebase);
exports.generateToken = functions.https.onCall((data, context) => {
const variable = data.variable;
const uid = context.auth.uid;
console.log("Function Trigerred");
if(uid !== null) {
console.log("UID: " + uid);
const requestPayload = JSON.stringify({
"variable": variable
});
console.log(requestPayload);
const config = {
hostname: 'API-HOST',
port: 443,
path: '/API-PATH',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
console.log(config);
const response = "";
const req = https.request(config, (res) => {
res.on('data', (data) => {
console.log(data);
res.send(data);
});
});
req.on('error', (error) => {
console.log(error);
res.end(error);
});
req.write(requestPayload);
req.end();
} else {
console.log("Invalid User");
res.send("Invalid User");
}
});
Call in App
Map<String, Object> data = new HashMap<>();
data.put("variable", "value");
FirebaseFunctions.getInstance()
.getHttpsCallable("generateToken")
.call(data)
.continueWith(task -> {
String result = (String) task.getResult().getData();
Log.e("1: ", result);
return result;
})
.addOnCompleteListener(task -> {
Log.e("2: ", "Complete");
if (!task.isSuccessful()) {
Exception e = task.getException();
if (e instanceof FirebaseFunctionsException) {
FirebaseFunctionsException ffe = (FirebaseFunctionsException) e;
FirebaseFunctionsException.Code code = ffe.getCode();
Object details = ffe.getDetails();
}
Log.e("3: ", task.getException().toString());
}
});
Firebase Console Log
{
Error: getaddrinfo ENOTFOUND API-HOST API-HOST:443 at GetAddrInfoReqWrap.onlookup [as oncomplete (dns.js:67:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'API-HOST',
host: 'API-HOST',
port: 443
}
However, when I tried hitting this API from Postman, I got the successful response.
I'm new to Node.js.