简单 XMLHttpRequest 失败,Access-Control-Allow-Origin header null

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

我正在尝试从 here 中公开的 API 中获取一个简单的随机引用。它基本上想要一个没有任何授权的 POST 请求。我想使用 XMLHttpRequests 来实现这一点。这是代码:

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);

无论我尝试什么,我的 XMLHttpRequests 总是失败并出现错误:

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

我在这里做错了什么?任何人都可以帮助编写代码并向我展示使用 forismatic API 工作的 XMLHttpRequest 示例吗?感谢您的帮助!

你没有做错任何事。您的浏览器期望 API 服务支持 CORS,但它不支持。你可以尝试 turn off CORS on your browser 来帮助调试,但你不应该那样去生产。

有可能服务支持CORS的小弟,JSONP

如果没有,并且如果此 API 服务不愿意现代化,并且如果您没有可用的替代方案,则您需要在服务器端进行 API 调用。