Reputation: 1139
I've retrieved some images from an API but they aren't appearing. Instead of the actual images appearing, the green and blue image icon is appearing in their places on my web page. What do I need to change/add in my code to get the images to appear?
let html = [];
fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key="*"')
.then((resp) => resp.json())
.then(function(data) {
data.results.slice(0, 4).forEach(res => {
html.push(`<h1>${res.title}</h1>`)
html.push(`<p>${res.url}</p>`)
html.push(`<p>${res.abstract}</p>`)
html.push(`<p>${res.published_date}</p>`)
html.push(`<img src='${res.multimedia[4]}.url'/>`)
})
document.getElementById("res").innerHTML = html.join("")
})
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<script src="index.js"></script>
</head>
<body>
<h1>Top Stories</h1>
<button class="accordion">Story 1</button>
<div class="panel">
<div id="res"></div>
</div>
<button class="accordion">Story 2</button>
<div class="panel">
<div id="accordion"></div>
</div>
<button class="accordion">Story 3</button>
<div class="panel">
<div id="accordion"></div>
</div>
<button class="accordion">Story 4</button>
<div class="panel">
<div id="accordion"></div>
</div>
</body>
Upvotes: 0
Views: 1959
Reputation: 410
I think you need to add src to your image instead of value like this:
html.push(`<img src='${res.multimedia[4].url}'/>`)
Upvotes: 5
Reputation: 8478
In HTML, images are defined with the
<img>
tag.The
<img>
tag is empty, it contains attributes only, and does not have a closing tag.The
src
attribute specifies the URL (web address) of the image:
let html = [];
fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=')
.then(response => response.json())
.then(data => {
// Prints result from `response.json()` in getRequest
data.results.slice(0, 4).forEach(res => {
html.push(`<h1>${res.title}</h1>`)
html.push(`<p>${res.url}</p>`)
html.push(`<p>${res.abstract}</p>`)
html.push(`<p>${res.published_date}</p>`)
console.log(res.multimedia[4].url);
html.push(`<img src='${res.multimedia[4].url}'/>`)
})
document.getElementById("res").innerHTML = html.join("")
})
<div id="res"></div>
You should use res.multimedia[4].url
for src of img
.
The res.multimedia[4]
is still an object with lot of info. You can just use the src url from the object and use it as img
source.
Upvotes: 3
Reputation: 316
Try this
html.push(`<img src='${res.multimedia[4]}'/>`)
instead of this
html.push(`<image>${res.multimedia[4]}</image>`)
Upvotes: 2