2017-09-17 1 views
0

HTTPメソッドルート(get、put、post ...)を使用してデータにアクセスし、処理する方法を理解しようとしています。これまでは、JSONデータをフェッチしてグローバル変数に格納することができました。ExpressでJSON変数を取得、保存、使用する

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.") 
}); 

私はHTTPがそのポケモンの数(JSONでpokedataと呼ばれている)XXXに関するいくつかのデータをhttp://localhost:3000/pokemon/XXX/ことを得る応答を送信したかったです。しかし、GET内のデータをループで任意の試みは、エラーをトリガ:

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 

が急行ドキュメントに関連する何かを見つけるように見えることはできません。どんな援助も好評です。

+0

pokedataの構造は何ですか?このエラーから、配列ではなくオブジェクトであるように見えます。 'for .. of'ループはオブジェクトに対しては機能しません。配列はもっとも使い慣れたものです。 –

+0

' '' fetch'''はいつ呼びますか?あなたが '' 'app.get'''の' 'console.log'''の' 'pokedata'''を見た場合、どうなっていますか? '{ポケモン:このような – Wainage

+0

@Wainage [{ID:1、 NUM: '001'、 名: 'フシギダネ' IMG「http://www.serebii.net/pokemongo/pokemon /001.png」 タイプ:[オブジェクト]、 高さ: '0.71メートル' 重量: '6.9キロ' キャンディ: 'フシギダネキャンディ'、 candy_count:25、 卵 '2キロ'、 spawn_chance:0.69、 avg_spawns:69、 spawn_time:'20:00' 、 乗数:[オブジェクト]、 弱点:[オブジェクト]、 next_evolution:[オブジェクト]}、 {id:2、 num: '002'、 名前: 'Ivysaur'、...]} ' – danielsto

答えて

3

pokedataはオブジェクトであり、反復処理はしたくありません。代わりに、あなたはポケモンの配列であるpokedata.pokemonを繰り返したいと思う。したがって、あなたのコードを少し修正するだけで、必要なのはすべてです:

for (let {name: n, weight: w, height: h} of pokedata.pokemon) { 
    res.send(n, w, h); 
} 
+0

スマートな質問にスマートな答え。ありがとうございました。ちょうど、人々が混乱しないように、 'console.log(n、w、h);' 'res.send(n、w、h);ではなく、' ' – danielsto

関連する問題