I'm unable to get either a success or failure from a simple axios call inside an Azure Function. Actually I can't get APIs to work in Azure full stop, but these are the simplest repo steps.
Code as follows:
const axios = require('axios');
module.exports = function (context, req) {
context.res = {
status: 200,
body: callAPI(),
headers: {
"Content-Type": "application/json"
}
};
context.done();
// Controlled logging
function Logger(msg) {
context.log(msg);
}
function callAPI() {
let res = { "state": "init" };
const config = {
method: 'get',
url: 'https://catfact.ninja/fact',
headers: {
'Cookie': 'XSRF-TOKEN=eyJpdiI6IjBwRFJSemp0ZTE3dEpRVWEzQm1jRnc9PSIsInZhbHVlIjoic1lMSDZ3cjlUdnRlQnJDQkQ4d2RhcWlPWFUvTjJjekdXSzVNSVBZUUlIQ3N5dVFLaE0ydHpESXhIeUNENlBSWFo1UTFJc1VML2dZakhvaTV0Q3B1V21iUmhYdndtck5uSFhZTVBJUEtuUnBocENmWkJCa2JQOWVYQjFBb1lCbnAiLCJtYWMiOiI5NThlMWE1ZWYyYjA4MmY2YTM0YjE1Njk1ZTgyMDA0YTQxNmIxMDkwN2I5Y2NlOGUzODljZDFlYTE3NzlkZTUwIiwidGFnIjoiIn0%3D; cat_facts_session=eyJpdiI6IktLMDZVVEdSMnN3UDJheDVwUERFc0E9PSIsInZhbHVlIjoib01nZUhMY21XQysyelQza3dxZVRLQ1cybW0zaXgzV0kweGg0eU5Wanpwdkt1QlY3bGZmTDhlU2JlMmJhNVB6VkttelhuLzQ4Q0lHR3BBOVRZTExNVXRDcys2QVliZVFYcUx2U01FSmRHc2tTaDA1NTdMa2V6dVNqcS9JeXN5cVAiLCJtYWMiOiIyYTVjYjM2ZDljZDdhZTgxM2Q3NDYzNWZkZjE3MDljNGNlNDJkOWRmMTlkYjMzMzc4OWFhNzk2ZDg1ODg4Y2QyIiwidGFnIjoiIn0%3D'
}
};
axios(config)
.then(function (response) {
res = response.data;
res.state = "OK"
Logger(`API called ok, res = ${res}`);
})
.catch(function (error) {
res.state = "FAL"
Logger(`API failed, err = ${error}`);
});
return res;
}
};
Response suggests the call never happened:
{
"state": "init"
}
Related
I am not geting any data from this code. It should fetch data from Zendesk API using Axios.
const { axios } = require("axios");
const CommonApiCaller = async (name, url, method, data, isFile = false) => {
let SUCCESS = false;
let ERROR = {};
let payload;
let config;
try {
if (method == "get") {
config = {
method: "get",
url: `${url}`,
};
}
}
config.headers = {
"Content-Type": "application/json",
Authorization:
"Basic basr64 encoded code",
};
let response = await axios(config);
after this there is nothing store in response directlly goes to finally else part
if (response && response.data) {
SUCCESS = true;
payload = response.data;
} else {
ERROR = {
message: "Invalid response",
code: response.status,
};
}
} catch (error) {
ERROR = {
message: error.message,
code: error.response?.status || error.code,
};
} finally {
if (SUCCESS) {
return {
SUCCESS: true,
data: payload,
};
} else {
return {
status: false,
data: ERROR,
};
}
}
};
module.exports = {
CommonApiCaller: CommonApiCaller,
};
When I call the main function then I got nothing from this why let response = await axios(config); in this nothing get the data after this line code not resone directly goes to and print this.
Hi I made a module and when I try to return the song name it is just undefined, the console.log just before it works though so I'm a little confused. The line after console.log(`"${songName}" by ${artistsList}`) is where the issue is, I try to return "${songName}" by ${artistsList} but the return is just undefined so I am a little stuck on why
Code: (This is the spotify.js module)
I call it with const Spotify = require("./spotify.js"), everything works up until I need to just return the song name using the Spotify.request() function
const axios = require("axios");
module.exports = {
token: "",
ref: "",
refresh: function () {
axios({
method: "post", //you can set what request you want to be
url: "https://accounts.spotify.com/api/token",
data:
`grant_type=refresh_token&refresh_token=${this.ref}`,
headers: {
Authorization:
"Basic ",
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(response => {
this.token = response.data.access_token
console.log(`Successfully refreshed token ${module.exports.token}`);
});
},
analyseSong: function (data) {
console.log(data)
const x = data;
//console.log(x)
if (x.is_playing) {
const songNameMatch = x.item.name.split("(");
var songName = x.item.name;
try {
const letter = songNameMatch[1].charAt(0);
letter.toLowerCase() == "f" ||
songNameMatch[1].toLowerCase().match(/^with/)
? (songName = songNameMatch[0].trim())
: false;
} catch (err) {
false;
}
var artistArray = [];
var artist;
const artists = x.item.artists;
//console.log(token)
for (artist in artists) {
artistArray.push(x.item.artists[artist].name);
}
//console.log(artistArray)
const artistsList = artistArray.join(", ");
//console.log(artistsList)
//console.log(`Currently playing: ${songName} - ${artistsList}`);
console.log(`"${songName}" by ${artistsList}`)
return `"${songName}" by ${artistsList}`;
} else {
return `Not currently listening to a song`;
}
},
request: function () {
axios
.get("https://api.spotify.com/v1/me/player/currently-playing", {
headers: { Authorization: `Bearer ${this.token}` }
})
.then(function (response) {
module.exports.analyseSong(response.data);
})
},
}
So I'm doing X=Spotify.request() trying to get the song name as X so I can output using IRC chat
There are a couple problems. .request() has no return value at all. So, it will never return anything other than undefined. You can fix that like this by adding two return statements, the first to return the promise itself and the second to make the return value from analyseSong() be the resolved value of that promise:
request: function () {
return axios
.get("https://api.spotify.com/v1/me/player/currently-playing", {
headers: { Authorization: `Bearer ${this.token}` }
})
.then(function (response) {
return module.exports.analyseSong(response.data);
})
},
Now Spotify.request() will return a promise that will resolve with the value returned from .analyseSong(response.data). You would use that promise like this:
Spotify.request().then(result => {
console.log(result);
}).catch(err => {
console.log(err);
});
I'm calling two methods in useeffect but when api1 get called it get executed till await axios.put and then api2 get called without getting the response from api1. And after getting a reponse from api2 it goes to api1 reponse and gets a reponse as undefined
useEffect(() => {
api1();
api2();
}, [])
const api1 = async () => {
try {
var requestModel = JSON.stringify({ UserId: userid, MenuName: menuname });
var requestBody = security.encrypt(requestModel);
axios.myHashData = security.computedHmac256(requestBody);
var config = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
await axios.put(axios.controllername + 'methodname', requestBody, config, { withCredentials: true })
.then(response => {
if (response.status === 200) {
//setapidata(response.data);
}
});
} catch (error) {
console.error(error.message)
}
}
const api2= async () => {
try {
var requestModel = JSON.stringify({ UserID: userid });
var requestBody = security.encrypt(requestModel);
axios.myHashData = security.computedHmac256(requestBody);
var config = { headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' } }
await axios.post(axios.controllername + 'methodname', requestBody, config, { withCredentials: true })
.then(response => {
if (response.status === 200) {
setapidata(response.data);
GetApis();
}
});
} catch (error) {
console.error(error.message)
}
}
If you want to wait for the api1 to execute before api2 is called you need to change the code for useEffect as below
useEffect(async() => {
await api1();
await api2();
}, [])
or
useEffect(() => {
api1().then(() => api2());
}, [])
To handle errors properly use try-catch block inside the useEffect if using await or use catch block if using .then
Also, another suggestion, if you are using a function inside useEffect make sure either the function is defined inside the same useEffect block or it is memorized either via useCallback or useMemo
I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request
I'm trying to make a request to an external API so that I can use the response data in the response of my own API, but I can't seem to get the response data on it`s own so that I can use it in my own API, how would I use module.exports to return the response data from the file where I'm making the external API request ?
var axios = require("axios");
var config = {
method: "get",
url: "https://some-api",
headers: {},
};
axios(config)
.then(function (response) {
//how can I export response.data from the file
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
console.log(response);
You can export it a a function from your module:
file: data.js
var axios = require("axios");
var config = {
method: "get",
url: "https://some-api",
headers: {},
};
exports.getData = () => {
return axios(config).then(function (response) {
console.log(JSON.stringify(response.data));
return response.data; // this returns the data
}).catch(function (error) {
console.error(error);
});
};
from another module (in the same folder):
const { getData } = require('./data');
getData().then(data => { ... });