我正在尝试将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。
答案 0 :(得分: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))