batilc February 2016

Simple XMLHttpRequest fails with Access-Control-Allow-Origin header null

I am trying to get a simple random quote from API exposed in here. It basically wants a POST request without any authorization. I want to achieve this using XMLHttpRequests. Here is the code:

var xhr = new XMLHttpRequest();
var forismaticUrl = 'http://api.forismatic.com/api/1.0/';
var params = 'method=getQuote&format=json&lang=en';

xhr.withCredentials = true;
xhr.responseType = 'json';
xhr.open('POST', forismaticUrl, true);

xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

xhr.onload = function(response) {
    console.log('helloooo', response);
    console.log(this);
    console.log(this.responseText);
};

xhr.send(params);

Whatever I tried, my XMLHttpRequests always fail with error:

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/. No 'Access-Control-Allow-Origin' header is present on the requested resource

What am I doing wrong here? Can anybody help with the code and show me working XMLHttpRequest example with the forismatic API? Thanks for the help!

Answers


code_monk February 2016

You are not doing anything wrong. Your browser is expecting the API service to support CORS, but it does not. You could try to turn off CORS on your browser to help with debugging, but you should not go to production like that.

It's possible that service supports CORS's younger and weaker brother, JSONP.

If not, and if this API service is unwilling to modernize, and if there are no alternatives available to you, you'll need to make your API calls server-side.

Post Status

Asked in February 2016
Viewed 3,343 times
Voted 12
Answered 1 times

Search




Leave an answer