简体   繁体   中英

How to embed ContextualWeb News API in an HTML page?

I am trying to embed ContextualWeb News API in a simple HTML page. Upon pressing a button, the news API should return a list of results. I would like to print the response to the console.

The request looks like that: (But they do not provide a complete HTML example)

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))

The Rapid API key can be obtained here: https://rapidapi.com/contextualwebsearch/api/web-search

Would like to have an HTML with a button, and output the results to the console or to a text box.

You can try something like this:

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));
}

Call a function inside the fetch that will deal with the result. If you are using pure JavaScript, you can try innerHTML to write the result.

I was able to figure it out. Here is the ContextualWeb News API request embedded in a simple HTML page. Upon pressing the button, the resulting JSON is written to the console.

<!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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM