维基百科上的 CORS 错误 API

CORS Error on Wikipedia API

我对如何在 React 中处理维基百科 api 调用感到有点困惑。我将 运行 保留在这个错误中:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource(...)

现在,我是 运行 提交表单时的一个操作,表单采用表单输入值并将其插入维基百科 api URL。我已经尝试过使用 JSONP,但我真的不想使用它,因为我听说它超级 hacky。

actions/index.js

import axios from 'axios';

const WIKI_URL = "https://en.wikipedia.org/w/api.php?action=query&format=jsonp&list=search&titles=";
const FETCH_ARTICLES = 'FETCH_ARTICLES';

export function fetchArticles(term) {
  const url = `${WIKI_URL}${term}`;
  const request = axios.get(url);

  return {
    type: FETCH_ARTICLES,
    payload: request
  }

如果需要,我绝对可以添加更多代码,但据我所知,这就是问题所在。

编辑:如果我必须使用 JSONP,我仍然无法使用。我相信 axios 不支持 JSONP,是否有更好的库可以使用?为什么有些 API 有跨源引用错误而有些没有?

为了在不使用 JSONP 的情况下解决这个问题,解决方案是使用一个代理服务器来接受您的请求,并将适当的 CORS headers 添加到响应中。作为起点,这将有助于作为参考:https://gist.github.com/pauloricardomg/7084524

删除 format=jsonp 并将 origin=* 添加到 WIKI_URL 值中的查询参数:

const WIKI_URL = "https://en.wikipedia.org/w/api.php?origin=*&action=query…";

参见the CORS-related docs for the Wikipedia backend

For anonymous requests, origin query string parameter can be set to * which will allow requests from anywhere.

至于 format 参数,JSON 输出是默认值,因此您无需指定。