Autocomplete API request fails using fetch()

  • 1
  • Problem
  • Updated 10 months ago
  • (Edited)
Using fetch() to retrieve JSON from the autocomplete api fails. See the code below:
// Request for JSON data<br> fetch("https://autocomplete.wunderground.com/aq?query=salt&cb=?",{method: "get", mode: "no-cors"})
    .then(function(response) {
      if (response.ok) {
        console.log("response OK");
        return response.json();
      } else {
        throw new Error("Something went wrong");
      }
    })
    .then(function(data) {
      // See the received data
      console.log(data);
});
Photo of Blaine Robertson

Blaine Robertson

  • 2 Posts
  • 1 Reply Like

Posted 10 months ago

  • 1
Photo of Blaine Robertson

Blaine Robertson

  • 2 Posts
  • 1 Reply Like
Further exploration has revealed that "no-cors" does not make any returned data available to the front-end, thus you are "cutting off your own nose" when using it. But, the autocomplete API server does not have a CORS header in place, so when CORS is used, an error is returned saying that the cross site origin prohibition is in place and data cannot be returned.

There are two possible solutions: 1) the autocomplete API needs to have a CORS header added to it (please!) or 2) a return type of JSONP must be used. However, the ES6 Fetch API does not support JSONP, so a different methodology has to be used.

To make things easy, it would really nice if a CORS header were added to the Autocomplete API server. Can this be done? Please.