在制作CORS请求时出现以下错误。有趣的是,这是在safari中工作,但不是在谷歌浏览器和Firefox。我一直在浏览所有内容,但没有在网络上找到任何解决方案。
我想发送json到服务器,但据我所知我需要将它发送到服务器之前,因此我使用JSON.stringify字符串,但最终我期待json结果从服务器。
这就是我正在卷曲的电话。 (我只是去尝试看看头)
HTTP/1.1 200 OK
Date: Tue, 18 Apr 2017 15:13:04 GMT
Server: Apache
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: POST, OPTIONS
Access-Control-Max-Age: 21600
Content-Length: 213
Content-Type: application/json
,这就是我在Chrome中获得网络选项卡上
和最后一部分我的代码
function foo(api_key, url, query, pdata, callback) {
var result = 'none';
if (typeof pdata != "undefined"){
var mydata = {"api_key": api_key, "query": query, "data": pdata };
}
else {
var mydata = {"api_key": api_key, "query": query};
}
$.ajax({
method : "POST",
url : url,
data: JSON.stringify(mydata),
contentType: "application/json;charset=UTF-8",
cache: false,
dataType: "json",
success : function(data) {
console.log("API call is working successfully!")
callback(data);
result = data
},
error: function(data, status, error) {
console.log("API call failed!")
}
});
return result;
}
这是我得到的错误。
XMLHttpRequest cannot load https://my_url. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
api.js:29 API call failed!`
我应该怎么做,更改或添加它使其在Chrome和Firefox中工作?
如果你的后端是不挑剔的要求'内容Type'头,你总是可以将其设置为'文/ plain'这使得它成为* *简单的要求,因此,避免了飞行前'OPTIONS'请求 – Phil
尝试使用'crossDomain:true'更新您的选项。这应该是自动的,但也许会失败? –
可能对未来的参考很有用,但请包括文本内容,而不是简单地发布代码的截图/图像。 – Terry