Not getitng the same response in postman and fetch

Viewed 131

I have this function to make a request to gyphy api

const getGifs = async () => {
        const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';
        const resp =  await fetch(url)
            .then(response => console.log(response));
        
}

In postman I get a json with the searched data but in javascript I get a response object, how can I get the searched data?

3 Answers

you are returning undefined because you are returning console.log() which is not right. Change it to response.body()


const fetch = require("node-fetch")

const getGifs =  () => {
        const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';

        const resp =fetch(url)
            .then(response => response.data);

        return resp;
        
}
console.log(getGifs());

According to the giphy api doc, the search endpoint returns a data element, which is an array of gifs. Just inspect your response object and see if it has a data element, then log response.data, not the full response

 .then(response => console.log(response.data));

The fetch API does not return the raw response a such. The object you're getting is one that can be transformed into what you need. Since you're expecting JSON data, then your code should be:

const getGifs = async () => {
        const url = 'https://api.giphy.com/v1/gifs/search?api_key=mykey&q=ps5&limit=5';
        const resp =  await fetch(url)
            .then(response => response.json())
            .then(jsonData => console.log(jsonData)) // the response you're expecting
        
}

The .json() method returns a Promise that resolves with your JSON parsed data.

Related