在 postman 和 fetch 中没有得到相同的响应

Not getitng the same response in postman and fetch

我有这个功能可以向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));
        
}

在 postman 中,我得到一个 json 和搜索到的数据,但在 javascript 中,我得到一个响应对象,我怎样才能得到搜索到的数据?

你返回 undefined 是因为你返回 console.log() 这是不对的。将其更改为 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());

根据giphy api doc,搜索端点returns一个数据元素,它是一个gifs数组。只需检查您的响应对象,看看它是否有数据元素,然后记录 response.data,而不是完整的响应

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

提取 API 不会 return 原始响应。您得到的对象是可以转换成您需要的对象。由于您需要 JSON 数据,因此您的代码应为:

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
        
}

.json() 方法 return 是一个使用您的 JSON 解析数据解析的 Promise。