0

我正在尝试将 ContextualWeb News API 嵌入到一个简单的 HTML 页面中。按下按钮后,新闻 API 应返回结果列表。我想将响应打印到控制台。

请求看起来像这样:(但他们没有提供完整的 HTML 示例)

const url ="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
const options = {
  method: 'GET',
  headers: {
    "X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "XXXXXXXX"
  },
}

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.error(e))

Rapid API 密钥可在此处获取: https ://rapidapi.com/contextualwebsearch/api/web-search

想要一个带有按钮的 HTML,并将结果输出到控制台或文本框。

4

2 回答 2

1

你可以尝试这样的事情:

fetch(url, options)
  .then(response => response.json())
  .then(data => showResults(data))
  .catch(e => console.error(e))

showResults(data) {
   data.map(news => console.log(news.title));
}

在 fetch 中调用一个函数来处理结果。如果您使用的是纯 JavaScript,您可以尝试使用 innerHTML 来编写结果。

于 2019-04-23T12:33:46.437 回答
0

我能够弄清楚。这是嵌入在简单 HTML 页面中的 ContextualWeb News API 请求。按下按钮后,生成的 JSON 将写入控制台。

<!doctype html>
<html>

<head>
</head>

<body>
    <div style="margin: 40px 40px; width: 450px;">

        <button onclick="makeGETRequest()">Make the News API call</button>

        <p>see console the for results</p>
    </div>
    <script>
        function makeGETRequest() {
            const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
            const options = {
                method: 'GET',
                headers: {
                    "X-RapidAPI-Host": "contextualwebsearch-websearch v1.p.rapidapi.com",
                    "X-RapidAPI-Key": "XXXXXXXXXXXXXXX"
                },
            }

            fetch(url, options)
                .then(response => response.json())
                .then(data => console.log(data))
                .catch(e => console.error(e))
        }
    </script>
</body>

</html>
于 2019-04-24T10:44:39.820 回答