如何使用 axios HTTP 客户端在 node.js 中使用 ContextualWeb 新闻 API?

How to use ContextualWeb News API in node.js using axios HTTP client?

我正在尝试将 ContextualWeb 新闻 API 集成到 node.js 应用程序中。 特别是,我想使用带参数的 axios 向新闻 API 端点发出 GET 请求。

以下代码有效,但它使用 fetch 并且参数嵌入在 url 中,这很不方便:

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

如何将代码转换为与 axios 一起工作? ContextualWeb 新闻 API 应该 return 一个包含相关新闻文章的结果 JSON。

这种方法应该有效:

const axios = require("axios");
const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI";
const config = {
    headers: {
        "X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
        "X-RapidAPI-Key": "XXXXXX" // Replace with valid key
    },
    params: {
        autoCorrect: false,
        pageNumber: 1,
        pageSize: 10,
        q: "Taylor Swift",
        safeSearch: false
    }
}

axios.get(url, config)
.then(response => console.log("Call response data: ", response.data))
.catch(e => console.error(e))