skip to Main Content

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>

consol 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 as well.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search