Node.js fetch returns empty data

I'm trying to get some data from an API using fetch, and the console log shows [], however, when I do the same request using Postman, it successfully returns a JSON. What am I doing wrong?

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");

Postman screenshot

Upvotes: 0

Views: 956

Answers (3)

jfriend00
jfriend00

Reputation: 707158

Your id is apparently encoded multiple times. If I decode it twice, I get this:

getDealInfo("X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8=");

And, that actually fetches this data.

{ 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 } }

So it, appears that the id value you're passing is incorrect. You can see that the node-fetch() code is working fine by just using it with the base URL: http://www.cheapshark.com/api/1.0/deals and that will return you JSON, confirming that the node-fetch() code works just fine and the issue is with your id value.

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160171

Using that ID I also get nothing.

Note that if you make the request with no id the IDs do not match your format, e.g.,

"dealID":"tnXImZO%2FYSnkve2w7O5fHy77qn0e8uvWFbkiT%2Fjb7r0%3D"

It looks like you have an extra URI encoding going on somewhere.

Upvotes: 0

Codebling
Codebling

Reputation: 11382

The problem is with your ID. You've escaped it twice.

getDealInfo("X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8%253D");

Id in your code is X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8%253D but in the screenshot it is X8sebHhbc1Ga0dTkgg59WgyM506af9oNZZJLU9uSrX8%3D. Look at the 3rd to last digit.

Upvotes: 0

Related Questions