Hi there
Having some trouble, I have a fetch request for the mars rover and I want to display the images on a webpage that I got back from json, How can I do this?
fetch('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=3415&camera=mast&page=1&api_key=DEMO_KEY')
.then(response => response.json())
.then(data => {
console.log(data)
let elem1 = document.getElementById('image')
data.photos.forEach(element => console.log(element.img_src))
elem1.innerHTML += `<div class="image-list"><img src ="${data.img_src}"</div>`
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="image"></div>
<script src="script.js"></script>
</body>
</body>
</html>
This url returns a JSON object which needs to be decoded
const photos = JSON.parse(txt);
Now photos is an array of photo records(objects)
This is the first object:
{
"id":947815,
"sol":3415,
"camera":{
"id":22,
"name":"MAST",
"rover_id":5,
"full_name":"Mast Camera"},
"img_src":"https://mars.nasa.gov/msl-raw-images/msss/03415/mcam/3415ML1016470050706993E01_DXXX.jpg",
"earth_date":"2022-03-15",
"rover":{
"id":5,
"name":"Curiosity",
"landing_date":"2012-08-06",
"launch_date":"2011-11-26",
"status":"active"}
},
I would also put the script tag into the head element
<script defer src="script.js"></script>
The defer attribute defers loading the file until the page has been loaded.
Could you please help me I want to display the images on a webpage that I got back from json on my website. Is there any way to do that?
Here is the jaw code to show the first image
fetch('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=3415&camera=mast&page=1&api_key=DEMO_KEY')
.then(response => response.json())
.then(data => {
let photoArray = data['photos'];
let elem1 = document.getElementById('image')
elem1.innerHTML += `<div class="image-list"><img src ="${photoArray[0].img_src}"</div>`
})