0

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!

batilc
  • 691
  • 1
  • 5
  • 16
  • @PatrickEvans I came up with that one as well. But I don't see any answer that says: `No, you cannot do it anyway using XMLHttpRequest`. Is the request possible with some configuration on the xhr object? – batilc Feb 08 '16 at 22:40

1 Answers1

1

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.

Community
  • 1
  • 1
code_monk
  • 9,451
  • 2
  • 42
  • 41
  • Thanks a lot for acknowledging! My code will be on production, so what is your suggested workaround? I found out two solutions which are both ugly: **1) Jquery ajax call with jsonp**: I dont want to include jquery only for this. **2) Make a script tag and change its src attribute**: Way uglier than jquery :( I think it is not possible to use jsonp format with xmlhttprequest, right? *btw there's no backend in my app, so there's no server-side* – batilc Feb 08 '16 at 22:49
  • **2** is basically what **1** does for jsonp anyway. If you have no *server side* and the API doesn't use CORS headers or JSONP, you're out of luck – Jaromanda X Feb 09 '16 at 03:37