0

I am learning JavaScript API project, fetch, then, catch. I coded along with a YouTube JavaScript API project. Every time I try it, 'catch' is not working.

let searchBtn=document.getElementById("search-btn");
let countryInp=document.getElementById("country-inp");
searchBtn.addEventListener("click", ()=>{
    let countryName=countryInp.value;
    let finalURL=`https://restcountries.com/v3.1/name/${countryName}?fullText=true`;
    console.log(finalURL);
    fetch(finalURL)
    .then((response)=>response.json())
    .then(data=>{
        console.log(data[0]);
        console.log(data[0].capital[0]);
        console.log(data[0].flags.svg);
        console.log(data[0].name.common);
        console.log(data[0].continents[0]);
        console.log(Object.keys(data[0].currencies)[0]);
    })
    .catch(()=>{
        if(countryName.lengh==0){
            result.innerHTML=`<h3>The input field cannot be empty</h3>`;
        }
        else{
            result.innerHTML=`<h3>Please enter a valid country name.</h3>`;
        }
    });
});
<button id="search-btn">Search</button>
<input id="country-inp" value="United Kingdom"></input>

Console box says this:

script.js:7          GET https://restcountries.com/v3.1/name/?fullText=true 404 (Not Found)
(anonymous) @ script.js:7

I tried

.catch(error => console.log(error))

but it was not working either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Megan
  • 1

2 Answers2

0

As I can see clearly in your code , the problem is caused by "countryName" variable which is empty "" , just check whether your countryInp is giving a value or not. Or you can just first hardcode the countryName variable to any country name for time being

As I have checked your Api is working fine.

One more thing you can check countryName.length inside the callback before calling api.

desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • Thank you for your answer. but the countryName is filled from index.html which is different file. everyghing else is working very well. just the error part is not working. when you do not put anything in the input box in index.html, it should go into .catch and show you the message that the input field cannot be empty but it does not show you the message and stop running, show you the message on console box. – Megan May 25 '23 at 19:24
0

First, take care because you have a typo in

if(countryName.lengh==0)...

If the console shows 404, probably the API is not working or you cannot send request to it.

Be careful, because the 'result' (element in DOM) is not declared in the code did you provide, and take care with the 'scopes' in javascript (you can see this in https://developer.mozilla.org/en-US/docs/Glossary/Scope).

I recommend you handling errors in a different way. You can create another file and create an Error Objects to handling errors. (see docs in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#utilizing_error_objects)