I'm working on a Microsoft Edge addon, I got the Pexels API to work with XMLHttpRequest but I am now trying to convert it to a Request object. I have searched multiple times for solutions but none worked.
Code:
// Get PEXELs Image
var page = Math.random()*250;
var url = "https://api.pexels.com/v1/search?query=cute+pets&page="+page.toString()+"&per_page=1";
var headers = new Headers();
headers.append('Authorization', key);
var er = new Request(url, {headers:headers})
var fr = fetch(er)
.then(res => res.json())
var r = fr
var photos = r.photos
console.log("photos", photos)
var raw = photos[0].src.original;
console.log("raw", raw);
// document.getElementById("image").src=raw;
Output:
photos undefined
[Cute Pet Pictures] [LOG/ERROR] TypeError: Cannot read properties of undefined (reading '0') at getImage(popup.js:15) at HTMLDocument.onBLoad(popup.js:25)
Object
- next_page: [link]
- page: 99
- per_page: 1
- photos: [{...}]
- prev_page: [link]
- total_results: 8000
Photos object (showing only parts needed by the script):
photos: Array(1)
- 0: {... src: {original: [URL] ...} ...}
I managed to fix it just by embedding the code below the "r" variable
var photos = r.photos
console.log("photos", photos)
var raw = photos[0].src.original;
console.log("raw", raw);
// document.getElementById("image").src=raw;
into the R variable's .then function.
The final result in the code:
var r = fr.then((json)=>{
print("json", json)
var photos = json.photos
console.log("photos", photos)
var raw = photos[0].src.original;
console.log("raw", raw);
document.getElementById("image").src=raw;
})