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

124
Visualizações
how can i fetch random images from Astronomy photo of the day api in Javascript website

I tried to fetch current images from NASA's Astronomy Photo of the Day (APOD) But now i am trying to fetch images randomly without using dates Is it possible? If yes then how?

here's the code

const fetchAPOD = async () => {
  try {
    const response = await fetch("https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY")
    const data = await response.json()
    displayData(data)
  } catch (error) {
    console.log(error)
  }
}

const displayData = data => {
  document.querySelector('.title').textContent = data.title
  document.querySelector('.date').textContent = data.date
  document.querySelector('.picture').src = data.url
  document.querySelector('.explanation').textContent = data.explanation
}

fetchAPOD()

which is working fine

all i want is to add feature to get images from the API randomly

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

count A positive integer, no greater than 100. If this is specified then count randomly chosen images will be returned in a JSON array. Cannot be used in conjunction with date or start_date and end_date.

https://jsfiddle.net/mplungjan/pymfg2uv/

const imgDiv = document.getElementById("imageDiv");

fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&count=3`)
.then(response => response.json())
.then(data => {
  imgDiv.innerHTML = data.map(item => `<div>
 <h3 class="title">${item.title} <span class="date">${item.date}</span></h3>
 <img src="${item.url}" />
 <p>${item.explanation}</p></div>`).join('')

})
.date { font-size: xx-small; }
<div id="imageDiv"></div>

Older answer with one random image from a date range

const img = document.getElementById("apod");
let date, start = Date.parse('2021-01-01'), end = new Date();
end.setDate(end.getDate()-1);
const getDate = () => { 
  date = new Date(Math.floor(Math.random() * (end - start + 1) + start)).toISOString().split('T')[0]; 
  return date
};

fetch(`https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&start_date=${getDate()}&end_date=${date}`)
.then(response => response.json())
.then(data => {
  img.src = data[0].url
})
<img id="apod" />

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