Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Code for Pexels image API not working - JavaScript

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] ...} ...}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
    })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!