Reputation: 69
I'm making an api call to the rescountries api. When I open up the console. I get the following error "Failed to load resource: the server responded with a status of 404 (Not Found)" However I seem to be getting an object printed out in the console that's coming from the restcountries api via the "console.log(data)" line. Is it to do with the API itself or something I did in my code? Thanks in advance.
"use strict";
const btn = document.querySelector(".btn-country");
const countriesContainer = document.querySelector(".countries");
const getCountryData = function (country) {
const request = new XMLHttpRequest();
request.open("GET", `https://restcountries.com/v3.1/name/${country}`);
request.send();
request.addEventListener("load", function () {
const [data] = JSON.parse(this.responseText);
console.log(data);
const html = `<article class="country">
<img class="country__img" src="${data.flag}"/>
<div class="country__data">
<h3 class="country__name">${data.name}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>π«</span>${(
+data.population / 100000
).toFixed(1)}</p>
<p class="country__row"><span>π£οΈ</span>${data.languages.eng}</p>
<p class="country__row"><span>π°</span>${data.currencies.symbol}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML("beforeend", html);
countriesContainer.lastElementChild.opacity = 1;
});
};
getCountryData("GB");
getCountryData("usa");
Upvotes: 0
Views: 1141
Reputation: 3917
You have 404 error because you have following divs <img class="country__img" src="πΊπΈ">
The src
attribute should be an URL - not a symbol. You have 2 calls one for UK and one for USA so you will have 2 such images and 2 404 Not found
errors will appear.
So your line of code where you produce this image i.e. <img class="country__img" src="${data.flag}"/>
should be probably <div>${data.flag}</div>
or similar.
Example:
"use strict";
const btn = document.querySelector(".btn-country");
const countriesContainer = document.querySelector(".countries");
const getCountryData = function (country) {
const request = new XMLHttpRequest();
request.open("GET", `https://restcountries.com/v3.1/name/${country}`);
request.send();
request.addEventListener("load", function () {
const [data] = JSON.parse(this.responseText);
console.log(data);
const html = `<article class="country">
<div class="country__img">${data.flag}</div>
<div class="country__data">
<h3 class="country__name">${data.name}</h3>
<h4 class="country__region">${data.region}</h4>
<p class="country__row"><span>π«</span>${(
+data.population / 100000
).toFixed(1)}</p>
<p class="country__row"><span>π£οΈ</span>${data.languages.eng}</p>
<p class="country__row"><span>π°</span>${data.currencies.symbol}</p>
</div>
</article>
`;
countriesContainer.insertAdjacentHTML("beforeend", html);
countriesContainer.lastElementChild.opacity = 1;
});
};
getCountryData("GB");
getCountryData("usa");
<div class="countries"></div>
Upvotes: 1