javascript - 无法过滤类似 JSON 的东西
问题描述
我正在使用来自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);
}
});
});
解决方案
这是 JSON。行星存储在results
. 所以结果是对象数组,现在您可以使用for
or遍历数组的所有元素in
。
您可以随意操作、循环、过滤器等。
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])
}
});
推荐阅读
- javascript - Threejs项目中移动和桌面浏览器之间画布的document.createElement不一致
- python - TypeError: dtype 对象的图像数据不能转换为浮点数
- reactjs - Styled-Components:具有多个道具/状态的条件样式
- android - 在 Android 问题中插入动态视图
- javascript - 如何获取鼠标单击的位置并在图像上添加标记(标记)?
- azure - 使用 Azure CNI 和站点到站点 VPN VNet 时如何从 pod 子网中拆分 AKS 群集子网
- kubernetes - 将 Kubernetes 中的各个点联系起来的良好做法是什么?
- amazon-web-services - 如何防止 Terraform 模块创建重复的 API 网关资源?
- javascript - 如何在一个导入的对象中组合 CSS 类
- javascript - 每个 React 类方法的“函数缺少返回类型”