FETCH JS:为什么在尝试获取资源时收到TypeError:NetworkError?

时间:2019-05-27 09:51:48

标签: javascript fetch

我不知道问题出在哪里。当将获取放入函数中时,在尝试获取资源时会引发错误TypeError:NetworkError,但是如果我将其放出,它将正确执行。为什么会这样?我在做什么错了?

我留下了代码,以便他们看到问题所在。谢谢!

HTML:

<body>
    <div class="container">
        <h1 class="main-title">POKEDEX</h1>
        <hr class="line">

        <div class="display-pokemon">
            <img class="img-pokemon"
                src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png">
                <h2 class="name-pokemon">BULBASAUR</h2>
        </div>

        <form class="form">
            <h3 class="form-title">Insert ID or NAME</h3>
            <input type="text" class="input-pokemon">
            <button id="searchPokemon" class="button-search"><i class="fab fa-searchengin"></i></button>
        </form>
    </div>

</body>

JS:

let buttonSearch;
    let inputPokemon;
    let namePokemon;

    //THIS CODE WORKS!
    fetch(`https://pokeapi.co/api/v2/pokemon/pikachu`)
        .then((response) => response.json())
        .then((pokemon) => {
            console.log(pokemon.name);
        })
        .catch((error) => {
            console.log(error)
        })


    function reload() {
        document.getElementById('searchPokemon').addEventListener('click', searchPokemon);
        inputPokemon = document.querySelector('form .input-pokemon').value.toLowerCase();
        namePokemon = document.querySelector('.name-pokemon');
    }

    function searchPokemon() {
        reload();
        console.log(inputPokemon);
        //THIS CODE INSIDE A FUNCTION IS NOT WORKING
        fetch(`https://pokeapi.co/api/v2/pokemon/pikachu`)
            .then((response) => response.json())
            .then((pokemon) => {
                console.log(pokemon.name);
            })
            .catch((error) => {
                console.log(error)
            })
    }

    reload();

最终目标是当按下#searchPokemon时,它会通过FETCH带给我该神奇宝贝的JSON。对于这个示例,为了理解我,我直接放置了PIKACHU,以便他们看到在函数内部,在外部函数正确运行时抛出的错误。

谢谢!

0 个答案:

没有答案