I'm very new to ES6 and JS world. I'm trying to create simple Utils method that will invoke the GET call using axios library and return the response.data as below:
AxiosUtils.js
const axios = require('axios');
const https = require('https');
const httpsAgent = new https.Agent({rejectUnauthorized: false});
class TestInvoker
{
constructor(url,body,hostName,securityContext)
{
this.url = url;
this.body = body;
this.hostName = hostName;
this.securityContext = securityContext;
}
invokeAgentGetCall()
{
let responseBody;
axios.get(this.url,{
httpsAgent:httpsAgent,
headers:{
"Accept": "application/json",
"Content-Type": "application/json",
"Hostname": `${this.hostName}`,
"prefer":"",
"X-AMAZON-SECURITY-CONTEXT": JSON.stringify(this.securityContext),
"AMAZON-Request-Id":'',
"Access-Control-Allow-Origin": true
}
}).then((res) => {
responseBody = res.data;
console.log(responseBody);
return responseBody;
}).catch(error => {
console.log(error);
})
}
}
module.exports = TestInvoker;
Calling the invokeAgentGetCall() method in another JS file as like below:
Test.js:
const TestInvoker = require("./AxiosUtils.js");
//This is public api for testing activity and no need any security header to call this get api
const result = new TestInvoker("https://jsonplaceholder.typicode.com/todos/1","","","");
console.log(result.invokeAgentGetCall());
Output:
node Test.js
undefined
{ userId: 1, id: 1, title: 'delectus aut autem', completed: false }
When I print the responseBody inside that class it shows the proper response but when I return that object and tried to print it from test.js it shows 'undefined'.
Can anyone help me to resolve this?