I call two APIs to get a random GIF from GIPHY. I want to call my gif()
function two times. Therefore, I use the promises
array. Right now I get an error when returning the object in the gif()
function.
return {
img: responseJSON.data[0].images.original.url,
word: wordJSON.word
}
img: responseJSON.data[0].images.original.url,
TypeError: Cannot read properties of undefined (reading 'images')
The strange thing is, I can access all the other values which are stored in responseJSON.data[0].images.original
for example size
Any suggestions?
app.get('/', (req, res) => {
const gifURL = 'https://api.giphy.com/v1/gifs/search?api_key=key&limit=1&rating=g';
const wordURL = 'https://api.api-ninjas.com/v1/randomword';
let options = {
method: 'GET',
headers: { 'x-api-key': '' }
}
promises = [gif(gifURL), gif(gifURL)];
async function gif(gifURL) {
const word = await fetch(wordURL, options);
const wordJSON = await word.json();
const response = await fetch(gifURL+'&q='+wordJSON.word);
const responseJSON = await response.json();
return {
img: responseJSON.data[0].images.original.url,
word: wordJSON.word
}
}
function renderResults() {
const values = Promise.all(promises)
.then((values) => {
console.log(values);
return res.render('home', {"values": values});
})
}
renderResults();
})
>Solution :
Try this to debug
What does your system show on this? We can’t do it easily here because we don’t have the API.
function get() {
const gifURL = 'https://api.giphy.com/v1/gifs/search?api_key=key&limit=1&rating=g';
const wordURL = 'https://api.api-ninjas.com/v1/randomword';
let options = {
method: 'GET',
headers: {
'x-api-key': ''
}
}
promises = [gif(gifURL), gif(gifURL)];
async function gif(gifURL) {
const word = await fetch(wordURL, options);
const wordJSON = await word.json();
console.log("wordJSON:", JSON.stringify(wordJSON, null, 2))
const response = await fetch(gifURL + '&q=' + wordJSON.word);
const responseJSON = await response.json();
console.log("responseJSON:", JSON.stringify(responseJSON, null, 2))
return {
img: responseJSON.data[0].images.original.url,
word: wordJSON.word
}
}
function renderResults() {
const values = Promise.all(promises)
.then((values) => {
console.log(values);
// return res.render('home', {"values": values});
})
}
renderResults();
}
get()