Warren Whipple
Warren Whipple

Reputation: 1070

How to properly CORS fetch from the Wikipedia API?

Chrome is allowing this CORS fetch, but FireFox is blocking it.

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) console error:

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).

A similar fetch to the GitHub API works on 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);
  });

Upvotes: 2

Views: 1766

Answers (1)

J-Christophe
J-Christophe

Reputation: 2070

As originally described here, since wikimedia website checks the origin using the query parameter origin and does not support cors-preflight-request, you have to make sure a GET method is sent.

Removing the following in your example ensures a GET request is sent:

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

Here the updated example:

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);
  });

Upvotes: 2

Related Questions