首页 > 解决方案 > 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");

邮递员截图

标签: node.js

解决方案


您的 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值上。


推荐阅读