设法获取 API 并在控制台中显示 JSON,需要帮助显示数据



var url = 'https://newsapi.org/v2/top-headlines?sources=talksport&apiKey='YOUR_API_KEY';

var req = new Request(url);
fetch(req)
.then(function(response) {
var results = (response.json());



console.log(results);
})

使用新闻 API,我使用此代码尝试为我的网站获取基于体育的文章。到目前为止,我设法控制台.log我从 API 获取的 JSON 文件。这将返回一个包含 10 篇文章的对象,这就是我一直在寻找的。但是,我希望能够控制台.log JSON 对象中的数据。我已经查看了几个YouTube/书面教程,试图找到我的答案以及我从中获得API的实际网站,但是它们没有提供更多信息,我不知所措。这里的任何帮助将不胜感激!

控制台日志对象图像

response.json返回一个承诺。您需要再链接一个承诺才能获得所需的数据。

这是代码:

var url = 'https://newsapi.org/v2/top-headlines?sources=talksport&apiKey='YOUR_API_KEY';

var req = new Request(url);
fetch(req)
.then(function(response) {
return response.json()
}).then(function(jsonResponse){
console.log(jsonResponse)
})

@Akshay Milmile是对的。你必须兑现你的承诺 请参阅代码:

var YOUR_API_KEY = "";
var url = 'https://newsapi.org/v2/top-headlines?sources=talksport&apiKey=' + YOUR_API_KEY;

var req = new Request(url);
fetch(req)
.then(function(response) {
return response.json();
console.log(results);
}).then(function(jsonResponse){
console.log(jsonResponse)
})

但是您的错误来自另一行:

var url = 'https://newsapi.org/v2/top-headlines?ources=talksport&apiKey='YOUR_API_KEY';

如果要保留它,则必须将其更改为:

var url = 'https://newsapi.org/v2/top-headlines?sources=talksport&apiKey=' + YOUR_API_KEY;

最新更新