简单XMLHttpRequest失败,并且Access-Control-Allow-Origin标头为null [英] Simple XMLHttpRequest fails with Access-Control-Allow-Origin header null

查看:1556
本文介绍了简单XMLHttpRequest失败,并且Access-Control-Allow-Origin标头为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从这里公开API的简单随机报价。它基本上想要一个POST请求没有任何授权。我想使用XMLHttpRequests实现这一点。这里是代码:

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

无论我试过,我的XMLHttpRequests总是失败,出现错误:

Whatever I tried, my XMLHttpRequests always fail with error:

XMLHttpRequest无法加载http://api.forismatic.com/api/1.0/。所请求的资源上没有Access-Control-Allow-Origin标头

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

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!

推荐答案

你没有做错什么。您的浏览器期望API服务支持CORS,但它不支持。您可以尝试关闭浏览器上的CORS 帮助调试,但是

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.

这种服务可能支持CORS的年轻和弱小的兄弟 JSONP 之间的差异。

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

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

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.

这篇关于简单XMLHttpRequest失败,并且Access-Control-Allow-Origin标头为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆