Build a Pokémon Search App Project - Build a Pokémon Search App

Tell us what’s happening:

Type Error: failed to fetch

my code is working when i load it in my browser, google chrome. but sometimes works in VS Code, sometimes doesn’t. when attempting the tests, it says fail to fetch.

Your code so far

WARNING

The challenge seed code and/or your solution exceeded the maximum length we can port over from the challenge.

You will need to take an additional step here so the code you wrote presents in an easy to read format.

Please copy/paste all the editor code showing in the challenge from where you just linked.

const searchInput = document.getElementById('search-input');
const searchBtn = document.getElementById('search-button');
const pokemonName = document.getElementById('pokemon-name');
const pokemonId = document.getElementById('pokemon-id');
const pokemonWeight = document.getElementById('weight');
const pokemonHeight = document.getElementById('height');
const pokemonTypes = document.getElementById('types');
const pokeScreen = document.getElementById('poke-screen');
const imgContainer = document.getElementById('img-container');

const hp = document.getElementById('hp');
const attack = document.getElementById('attack');
const defense = document.getElementById('defense');
const specialAttack = document.getElementById('special-attack');
const specialDefense = document.getElementById('special-defense');
const speed = document.getElementById('speed');

const pokeIndex = 'https://pokeapi-proxy.freecodecamp.rocks/api/pokemon';


// fetch the API
const fetchData = async () => {
    try {
        const res = await fetch(pokeIndex);
        const data = await res.json();
        showInfo(data);
        }

    catch (err) {
        console.log(err);
    }
};



const showInfo = (data) => {
    pokemonTypes.innerHTML = '';

    let inputStringToLower = searchInput.value.toLowerCase();
    const {results} = data;
    let pokemonData = [];
    
    let count = 0;
    
    for (let i = 0; i < results.length; i++) {

        if (results[i].id == searchInput.value || results[i].name == inputStringToLower) {
            count++;

            pokemonName.textContent = results[i].name.toUpperCase();
            pokemonId.textContent = `#${results[i].id}`;

            fetch(results[i].url).then((res2) => res2.json()).then((data2) => {
            pokemonData = data2;
            pokemonWeight.textContent = `Weight: ${pokemonData.weight}`;
            pokemonHeight.textContent = `Height: ${pokemonData.height}`;
            pokemonData.types.forEach((arr) => {
                pokemonTypes.innerHTML += `
                <div class='${arr.type.name} type-divs'>
                    <p>${arr.type.name.toUpperCase()}</p>
                </div>
                `;
            })
            imgContainer.innerHTML = `<img src="${pokemonData.sprites.front_default}" alt="${results[i].name}" id="sprite">`;
            // get stats into their divs
            pokemonData.stats.forEach((arr) => {
                switch (arr.stat.name) {
                    case 'hp':
                        hp.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    case 'attack':
                        attack.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    case 'defense':
                        defense.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    case 'special-attack':
                        specialAttack.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    case 'special-defense':
                        specialDefense.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    case 'speed':
                        speed.innerHTML = `
                        <p>${arr.base_stat}</p>
                        `;
                        break;
                    default:
                        return;
                }
                
            });

            }).catch((err2) => {
                console.log(err2);
            })

        }
    };

    if (count === 0) {
        alert('Pokemon not found');
    }

};

// button clicks
searchBtn.addEventListener('click', fetchData);
searchInput.addEventListener('keydown', (e) => {
    if (e.key === 'Enter'){
        fetchData();
    }
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pokemon Search App</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <main>

        <h1>Pok&eacute;mon Search App</h1>

        <div class="container">

            <form action="#">
                <label for="search-input">Search for Pok&eacute;mon Name or ID:</label>
                <div class="search-field">
                    <input type="text" id="search-input" required>
                    <button type="button" id="search-button">Search</button>
                </div>
            </form>

            <div id="poke-screen">

                <div class="poke-name-id together">
                    <p id="pokemon-name"></p>
                    <p id="pokemon-id"></p>
                </div>

                
                <div class="size together">
                    <p id="weight"></p>
                    <p id="height"></p>
                </div>
                
                <div id="img-container"></div>

                <div id="types" class="together"></div>

            </div>

            <div id="stats">
                
                <div class="purple-grid">
                    <p class="bold">Base</p>
                </div>
                <div class="purple-grid">
                    <p class="bold">Stats</p>
                </div>

                <div class="purple-grid">
                    <p>HP:</p>
                </div>
                <div class="purple-grid" id="hp"></div>

                <div class="purple-grid">
                    <p>Attack:</p>
                </div>
                <div class="purple-grid" id="attack"></div>

                <div class="purple-grid">
                    <p>Defense:</p>
                </div>
                <div class="purple-grid" id="defense"></div>

                <div class="purple-grid">
                    <p>Sp. Attack:</p>
                </div>
                <div class="purple-grid" id="special-attack"></div>

                <div class="purple-grid">
                    <p>Sp. Defense:</p>
                </div>
                <div class="purple-grid" id="special-defense"></div>

                <div class="purple-grid">
                    <p>Speed:</p>
                </div>
                <div class="purple-grid" id="speed"></div>

            </div>

        </div>

    </main>
    
    <script src="script.js"></script>
</body>
</html>

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36

Challenge Information:

Build a Pokémon Search App Project - Build a Pokémon Search App

never mind I just figured it out.

You should update your post with the information. If someone before you had the same issue and figured it out and posted the solution you wouldn’t have had to make the thread.

When asking for help and figuring it out it is just a reasonable thing to post the solution.


Anyway.

The objects returned by the http://pokeapi-proxy.freecodecamp.rocks/api/pokemon endpoint are not https if you look at the url property. Which will cause a CORS mixed content issue.

{
  "id": 3,
  "name": "venusaur",
  "url": "http://pokeapi-proxy.freecodecamp.rocks/api/pokemon/3/"
}

You can run a replace on them and replace http with https (or don’t use that method of fetching each Pokemon)

I will do that in the future. Thanks. And that is exactly what it was.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.