【发布时间】:2018-02-26 10:02:33
【问题描述】:
我一直在努力理解如何使用 HTTP 方法路由(get、put、post...)来访问和处理数据。到目前为止,我已经能够获取 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 GET 发送到http://localhost:3000/pokemon/XXX/,其中包含有关神奇宝贝编号 XXX 的一些数据(在名为 pokedata 的 JSON 中)。但是,任何在 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
似乎无法在 express 文档中找到任何相关内容。任何帮助都会受到好评。
【问题讨论】:
-
pokedata的结构是什么?从您得到的错误来看,它似乎是一个对象,而不是一个数组。
for .. of循环不适用于对象,仅适用于可迭代对象(数组是最熟悉的可迭代对象) -
你什么时候打电话给
fetch?如果你console.logpokedata中的app.get,会是什么样子? -
@Wainage 像这样:
{ 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', ... ]}
标签: javascript json node.js express ecmascript-6