Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda