如何在HTML页面中嵌入ContextualWeb News API?

问题描述 投票:0回答:2

我试图在一个简单的HTML页面中嵌入ContextualWeb News API。按下按钮后,新闻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,并将结果输出到控制台或文本框。

javascript html api
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来编写结果。


0
投票

我弄清楚了。以下是嵌入在简单HTML页面中的ContextualWeb新闻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>
© www.soinside.com 2019 - 2024. All rights reserved.