首页 > 解决方案 > 如何在 JavaScript 中向 ContextualWeb 图像搜索 API 发出 GET 请求?

问题描述

我正在使用RapidAPI访问ContextualWeb图像搜索 API。给出的代码示例仅适用于服务器端: https ://rapidapi.com/contextualwebsearch/api/web-search/

我正在尝试将 API 集成到 React JS 应用程序中。如何在JavaScript中发出 GET 请求?

下面是来自 Rapid API 网站的CURL示例:

curl --get --include 'https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false' \
  -H 'X-RapidAPI-Host: contextualwebsearch-websearch-v1.p.rapidapi.com' \
  -H 'X-RapidAPI-Key: XXXXXXXX'

图像搜索 API 应返回结果 JSON。

标签: javascriptimageapiwebsearch

解决方案


给定的curl请求转换为后续fetch API(由浏览器实现)请求。

const url ="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/ImageSearchAPI?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))

推荐阅读