skip to Main Content

Im trying to develop an app like wordle with javascript and wiktionary api.

So, when i try to send fetch request using this code:

const url = `https://en.m.wiktionary.org/w/api.php?action=query&titles=apple&format=json`;

fetch(url)
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

I receive "failed to fetch" error.

I also tryed to make this using XMLHttpRequest with


const url = `https://en.wiktionary.org/w/api.php?action=query&titles=apple&format=json`;

const xhr = new XMLHttpRequest();

xhr.open("GET", url, true);

xhr.onreadystatechange = function() {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    const response = JSON.parse(xhr.responseText);
    console.log(response);
  } else if (xhr.readyState === XMLHttpRequest.DONE) {
    console.error("error:", xhr.status);
  }
};

xhr.send();

This code also returns a 0 error.
So, how to parse this json data from wiktionary without jquery?

2

Answers


  1. Chosen as BEST ANSWER

    So, if it wiil help anyone in future As @HeikoTheißen said, CORS block access and i fixed that with adding origin=* to the link!


  2. I’ve debugged the issue with the browser console and found the following error message.

    "From origin ‘https://example.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled."

    Since, it’s a CORS policy issue, you may need to try running your code from a local server or using a browser extension that allows you to bypass CORS restrictions during development.

    However, you can try the following alternative methods to fetch data:

    JSONP fetch method

    const url = 'https://en.m.wiktionary.org/w/api.php?action=query&titles=apple&format=json&callback=processData';
    
    function processData(data) {
      console.log(data);
    }
    
    const script = document.createElement('script');
    script.src = url;
    document.head.appendChild(script);

    Adding origin=* parameter to the fetch URL

    As said in the previous answer, it also works.

    const url = `https://en.m.wiktionary.org/w/api.php?action=query&titles=apple&format=json&origin=*`;
    
    fetch(url)
      .then(response => response.json())
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.error("Error:", error);
      });

    If you’re running this code from a web page hosted on a different domain other than "en.m.wiktionary.org," the browser may block the request due to CORS restrictions. Try any of the above methods, definitely one of them will work for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search