cors - 如何正确从 Wikipedia API 获取 CORS?

标签 cors wikipedia-api

Chrome 允许这种 CORS 获取,但 FireFox 阻止它。

fetch(
  "https://en.wikipedia.org/w/api.php?action=query&titles=San_Francisco&prop=images&imlimit=20&origin=*&format=json&formatversion=2",
  {
    method: "GET",
    headers: {
      "User-Agent": "someone"
    }
  }
)
  .then(response => response.json())
  .then(json => {
    console.log(json);
  })
  .catch(error => {
    console.log(error.message);
  });

Firefox (61.0.1 Mac) 控制台错误:

Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at
https://en.wikipedia.org/w/api.php?action=query&titles=San_Francisco&prop=images&imlimit=20&origin=*&format=json&formatversion=2.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

与 GitHub API 类似的获取也适用于 Firefox。

fetch(
  "https://api.github.com",
  {
    method: "GET",
    headers: {
      "User-Agent": "someone"
    }
  }
)
  .then(response => response.json())
  .then(json => {
    console.log(json);
  })
  .catch(error => {
    console.log(error.message);
  });

最佳答案

如最初所述here ,因为 wikimedia 网站使用查询参数 origin 检查来源,并且支持 cors-preflight-request ,您必须确保发送 GET 方法。

删除示例中的以下内容可确保发送 GET 请求:

headers: {
  "User-Agent": "someone"
}

这里是更新的示例:

fetch(
  "https://en.wikipedia.org/w/api.php?action=query&titles=San_Francisco&prop=images&imlimit=20&origin=*&format=json&formatversion=2",
  {
    method: "GET"
  }
)
  .then(response => response.json())
  .then(json => {
    console.log(json);
  })
  .catch(error => {
    console.log(error.message);
  });

关于cors - 如何正确从 Wikipedia API 获取 CORS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51575656/

相关文章:

处理公用文件夹中的图像文件时 Laravel CORS 问题?

javascript - 无法让维基百科的 API 工作

wikipedia - 获取维基百科文章的第一段(仅文本)返回不期望的结果

count - 以编程方式从 MediaWiki wiki 获取文章总数

javascript - Googlebot 和空 CORS 响应

javascript - 用户在 three.js 中上传纹理

node.js - 无法在 Express 中设置标题

python - 自动解析消歧页面

javascript - 从维基百科解析请求中检索 pageid

Spring CORS No 'Access-Control-Allow-Origin' header 存在