【问题标题】:Fetch, store and use JSON variable with express通过 express 获取、存储和使用 JSON 变量
【发布时间】: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


【解决方案1】:

pokedata 是一个对象,您不想对其进行迭代。相反,您想迭代pokedata.pokemon,这是一个口袋妖怪数组。因此,只需对您的代码稍作修改即可:

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

【讨论】:

  • 聪明地回答一个不那么聪明的问题。谢谢你。只是想指出它应该是console.log(n, w, h); 而不是res.send(n, w, h);,以免人们感到困惑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-18
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
  • 2021-12-29
相关资源
最近更新 更多