Simple XMLHttpRequest fails with Access-Control-Allow-Origin header null [duplicate]

旧时模样 提交于 2019-12-12 04:04:45

问题


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!


回答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.



来源:https://stackoverflow.com/questions/35280550/simple-xmlhttprequest-fails-with-access-control-allow-origin-header-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!