如何正确地从维基百科 API 获取 CORS?
How to properly CORS fetch from the 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, since wikimedia website checks the origin using the query parameter origin
and does not support 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);
});
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, since wikimedia website checks the origin using the query parameter origin
and does not support 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);
});