1

I've been struggling trying to understand how to access and and process data using HTTP method routes (get, put, post...). So far, I've been able to fetch the JSON data and store it in a global variable.

var pokedata;

fetch('https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json')
    .then(function (res) {
        return res.json();
    }).then(function (json) {
        pokedata = json;
    }).catch(function () {
        console.log("It was not possible to fetch the data.")
});

I wanted to send responses HTTP GETs to http://localhost:3000/pokemon/XXX/ with some data about that Pokémon number XXX (which is in the JSON called pokedata). However, any attempt at looping through the data inside GET, triggers the error:

    app.get('/pokemon/:pokemonid', function (req, res) {
        //not the desired behaviour but a sample of what doesn't work.
        for (let {name: n, weight: w, height: h} of pokedata) {
            res.send(n, w, h); 
        }
    });

    TypeError: pokedata[Symbol.iterator] is not a function

Can't seem to find anything related in the express docs. Any help is well received.

3
  • what is the structure of pokedata? From the error you're getting it seems that it's an object, not an array. for .. of loops don't work on objects, just iterables (with arrays being the most familiar iterable) Commented Sep 17, 2017 at 23:21
  • When do you call fetch? If you console.log the pokedata in the app.get, what does it look like? Commented Sep 17, 2017 at 23:28
  • @Wainage like this: { pokemon: [ { id: 1, num: '001', name: 'Bulbasaur', img: 'http://www.serebii.net/pokemongo/pokemon/001.png', type: [Object], height: '0.71 m', weight: '6.9 kg', candy: 'Bulbasaur Candy', candy_count: 25, egg: '2 km', spawn_chance: 0.69, avg_spawns: 69, spawn_time: '20:00', multipliers: [Object], weaknesses: [Object], next_evolution: [Object] }, { id: 2, num: '002', name: 'Ivysaur', ... ]} Commented Sep 17, 2017 at 23:36

1 Answer 1

3

pokedata is an object, and you don't want to iterate on it. Instead you want to iterate on pokedata.pokemon, which is an array of the pokemon. So a small modification to your code is all that's needed:

for (let {name: n, weight: w, height: h} of pokedata.pokemon) {
    res.send(n, w, h); 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Smart answer to a not that smart question. Thank you. Just wanted to point out that it was supposed to be console.log(n, w, h); not res.send(n, w, h); so that people don't get confused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.