javascriptjquerywikidata-api

Querying Wikidata API using Javascript shows error related to CORS


What I know

Getting data from the Wikidata API using curl

I know that it is possible to get data of Wikidata items through the Wikidata API. The following code block shows a shell command that uses curl to get the data of the Wikidata item Q549037.

$ curl -s 'https://www.wikidata.org/w/api.php?format=json&action=wbgetentities&ids=Q549037'
$ curl -s 'https://www.wikidata.org/w/api.php?format=json&action=wbgetentities&ids=Q549037' | jq | head -n 10
{
  "entities": {
    "Q549037": {
      "pageid": 517337,
      "ns": 0,
      "title": "Q549037",
      "lastrevid": 1899479542,
      "modified": "2023-05-19T21:53:09Z",
      "type": "item",
      "id": "Q549037",

Getting data from the Wikidata API using jQuery

I also know that it is possible to use jQuery to do the same. The following code block shows HTML code that uses Jquery to get the data of the Wikidata item Q549037.

<body>
  <p>This is a paragraph.</p>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script>
    $.ajax({
      url: 'https://www.wikidata.org/w/api.php?format=json&action=wbgetentities&ids=Q549037',
      dataType: 'jsonp'
    })
  .done(function(data) {
    if (console && console.log)
      console.log(data)
  })
  </script>
</body>

The following screenshot shows Mozilla Firefox 113.0 and the console opened showing the data that was obtained through the Wikidata API.

enter image description here

The problem

I'm now trying to query Wikidata using Javascript but without using Jquery. The following code block shows what I've written.

<script>
  const myHeaders = new Headers()
  myHeaders.append("Access-Control-Allow-Origin", "*")
  const request = new Request('https://www.wikidata.org/w/api.php?format=json&action=wbgetentities&ids=Q549037', {
    method: "GET",
    headers: myHeaders
  })

  fetch(request)
  .then((response) => {
    if (response.status === 200) {
      return response.json();
    } else {
      throw new Error("Something went wrong on API server!");
    }
  })
  .then((response) => {
    console.debug(response);
  })
  .catch((error) => {
    console.error(error);
  })
</script>

It fails with the following error in Mozilla Firefox 113.0

The following screenshot shows Mozilla Firefox 113.0 showing the errors that were mentioned above.

enter image description here

The question

What am I doing wrong? I want to be able to query Wikidata using Javascript, but without having to use a heavy library such as Jquery.


Solution

  • You need to add &origin=* to your request URL. See API:Cross-site requests § Unauthenticated CORS Requests.