如何获取来源正确的维基百科地理搜索?

how to fetch a wikipedia geosearch with a correct origin?

我想在我的交互式地图中添加“wikipedia-geosearch”功能。 这是该操作最简单的代码,第一次尝试:

const buildWikiGeoSearch = (cn, rd, [lon,lat]) =>
    `https://${cn}.wikipedia.org/w/api.php?action=query&list=geosearch&format=json&gsradius=${rd}&gscoord=${lat}|${lon}`;
let query = buildWikiGeoSearch("fr", 2000, [6.94,49.21]);
console.log(`WikiGeoSearch = ${query}`);
const jsonr = fetch(query)
    .then(a => console.log("geoSearch ok") || a.json())
    .then(b => console.log(JSON.stringify(b)))
    .catch(e => console.log("geoSearch crash:", e));

它失败了,抛出一个 TypeError: Failed to fetch(不是很明确!)。

第二次尝试,添加&origin=*:

const buildWikiGeoSearch = (cn, rd, [lon,lat]) =>
    `https://${cn}.wikipedia.org/w/api.php?action=query&list=geosearch&format=json&gsradius=${rd}&gscoord=${lat}|${lon}`;
let query = buildWikiGeoSearch("fr", 2000, [6.94,49.21]) + "&origin=*"; // ***CHANGE***
const jsonr = fetch(query)
    .then(a => console.log("geoSearch ok") || a.json())
    .then(b => console.log(JSON.stringify(b)))
    .catch(e => console.log("geoSearch crash:", e));

有效,但我想了解一下

origin=*a part of the MediaWiki API. MediaWiki uses the parameter to return correct Cross-Origin Resource Sharing (CORS) headers on its HTTP response, which tells your browser that it's okay for your app to load that data. origin=* means that the API should allow any origin ("*" stands for wildcard).

使用 origin=* 非常安全。