node.js - Node.js fetch 返回空数据
问题描述
我正在尝试使用从 API 获取一些数据fetch
,并且控制台日志显示[]
,但是,当我使用 Postman 执行相同的请求时,它成功返回了 JSON。我究竟做错了什么?
let fetch = require("node-fetch");
const url_deals = 'http://www.cheapshark.com/api/1.0/deals';
function getDealInfo(dealID){
let new_url = new URL(url_deals + "?id=" + dealID);
fetch(new_url, {method : 'GET'})
.then(data =>{
data.json().then(out => {
console.log(out);
})
})
}
getDealInfo("X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8%253D");
解决方案
您的 id 显然被多次编码。如果我将它解码两次,我会得到:
getDealInfo("X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8=");
而且,这实际上获取了这些数据。
{ gameInfo:
{ storeID: '1',
gameID: '93503',
name: 'BioShock Infinite',
steamAppID: '8870',
salePrice: '29.99',
retailPrice: '29.99',
steamRatingText: 'Overwhelmingly Positive',
steamRatingPercent: '95',
steamRatingCount: '61901',
metacriticScore: '94',
metacriticLink: '/game/pc/bioshock-infinite',
releaseDate: 1364169600,
publisher: 'N/A',
steamworks: '1',
thumb:
'https://steamcdn-a.akamaihd.net/steam/apps/8870/capsule_sm_120.jpg?t=1568739647' },
cheaperStores:
[ { dealID: 'fq0cNHiR3Z4TpZyV7WH865C1%2BCBlmufYUc%2Bu2HqyUHE%3D',
storeID: '27',
salePrice: '26.99',
retailPrice: '29.99' } ],
cheapestPrice: { price: '5.27', date: 1543553226 } }
因此,您传递的 id 值似乎不正确。您可以看到node-fetch()
代码运行良好,只需将其与基本 URL 一起使用:http://www.cheapshark.com/api/1.0/deals
这将返回 JSON,确认node-fetch()
代码运行良好并且问题出在您的id
值上。
推荐阅读
- javascript - 如何在 React Hooks 中将两个状态合并为单个状态?
- java - Java HashMap.size() 函数如何在内部工作?
- java - 设置待处理意图/广播接收器的问题
- c# - .NetCore 不引用实体框架错误
- typescript - Mocha/Chai:使用错误消息测试抛出的错误
- python - 使用正则表达式执行分配属性
- powershell - 将 ansible 变量传递给包含花括号的 powershell 代码
- php - 如何根据选择的其他选择选项更改选择选项?
- github - 在公共存储库中发布 npm 密钥
- python - 试图设置 ipdb.set_trace(): RuntimeError: There is no current event loop in thread 'Thread-....'