Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda