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

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

我正在尝试将ContextualWeb News 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应返回带有相关新闻文章的结果JSON。

javascript api search news-feed
1个回答
1
投票

这种方法应该有效:

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))
© www.soinside.com 2019 - 2024. All rights reserved.