【问题标题】:Can't filter JSON-like thing无法过滤类似 JSON 的东西
【发布时间】:2018-10-12 11:26:35
【问题描述】:

我正在使用来自https://swapi.co/ 的数据在 node.js 中编写一个应用程序。我的一项功能需要检查我的数据库中是否存在指定的行星,如果不存在,api 应该从 swapi 下载行星的数据,但不知何故我无法检索有关按名称指定的行星的数据,我只能获取格式提供的数据此链接:https://swapi.co/api/planets/?format=json

  • 当我尝试过滤或将此结果转换为 JSON 或过滤它时,nodejs 给了我一个错误,但在控制台中记录响应的正文显示它看起来很像 JSON,所以,问题是我如何才能拉出指定行星反应的身体?

方法代码:

router.route('/Planets')
    .post(function (req, res) {
        var planet = new Planet(req.body);
        //validate planet.name here
        Planet.find({name: planet.name}, function (err, planet) {
            if (err) {
                res.status(500).send(err);
            }
            if (planet == '') {
                console.log("action: planet not found");
                request.get(
                    'https://swapi.co/api/planets/?format=json',
                    {json: true},
                    function (error, response, body) {
                        console.log(body);
                    }
                );
                // planet.save();
                res.status(201).send(planet);
            } else {
                res.status(201).send(planet);
            }
        })
    })
    .get(function (req, res) {
        Planet.find(function (err, planets) {
            if (err) {
                res.status(500).send(err);
            } else {
                res.json(planets);
            }
        });
    });

【问题讨论】:

标签: javascript json node.js filtering response


【解决方案1】:

这是 JSON。 行星存储在results。 所以结果是对象数组,现在您可以使用forin 遍历数组的所有元素。

您可以随意操作、循环、过滤器等。

fetch("https://swapi.co/api/planets/?format=json")
  .then(res => res.json())
  .then(res => {
    console.log(res);
    // Array of planets stored in res.results
    for (let i=0; i<res.results.length; i++) {
      console.log("Name:", res.results[i].name, "Data:", res.results[i])
    }
  });

【讨论】:

  • 感谢您的回答,这就像一个魅力,但我想问另外两件事:-如何从 fetch 中的另一个 js 文件调用函数?将它们与require一起使用后,我的所有函数都在编译文件后立即运行? - 有没有办法从身体外部获取数据:我想取出指定的行星,将其保存到数据库中并以状态 201 发送它,但不能在 fetch() 内部进行。
猜你喜欢
  • 2013-03-11
  • 2011-08-24
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 2011-06-16
  • 2020-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多