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).
在Firefox上也可以使用与GitHub API类似的抓取方式。
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);
});
答案 0 :(得分:1)
如最初所述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);
});