0

Hi Maybe you can help enlighten me :)

Im trying to make a simple Quote Generator app in pure Javascript (no jQuery), and Im trying to load the following api

https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en

but I keep getting the following error, whether on local host or if I upload it to a host:

Failed to load https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:50969' is therefore not allowed access.

The code Im using is the below:

// JavaScript Document

var xhr = new XMLHttpRequest();
xhr.open('GET',"https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en",true);
xhr.responseType = 'text';
xhr.send();

xhr.onload = function() {
    if(xhr.status === 200) {
        var myStuff = JSON.parse(xhr.responseText);
        console.log(myStuff);

       }
}

If I use an API url with a .json at the end such as:

http://api.wunderground.com/api/3a9c68e56dd0e1fb/conditions/q/90210.json

it works fine, but if I use anything without the .json it gives me that error.

Ive searched all day and cant find a solution and I really don't want to use jQuery for this.

GNova
  • 79
  • 1
  • 9

2 Answers2

0

It's about CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS this should help - actually there is no way you could do it from website. your request will be blocked by your browser. what you can probably do is to write backend proxy that will do it.

bunny1985
  • 762
  • 6
  • 21
-1

quick and easy answer - You are requesting a resource that is only supposed to be requested from the same origin, meaning from https://forismatic.com

It works with JSON because JSON works in a bit different way, but for the normal API call to work, someone on the API server would have to allow your website's origin for it to be able to make secure calls to the server.

You can try using JSONP for the request and see if it helps.

Ramon Diogo
  • 1,630
  • 2
  • 14
  • 9
  • 1
    "JSON because JSON works in a bit different way" — JSON does not work in a different way. The server has been configured to tell the browser that cross-origin requests are OK, but only when the end point is supposed to return JSON. – Quentin Mar 06 '18 at 13:29
  • @Quentin Well put, exactly what I meant, just in simple words. – Karolis Stakėnas Mar 06 '18 at 13:33