从 API CORS 获取数据
get data from API CORS
我正在尝试从不支持 CORS 的服务器获取 json 数据。我读到 Jsonp 是针对这种情况的解决方案,但我仍然无法使其工作:
我的代码:
var headers = {
'Authorization': 'Bearer ' + 'token',
'Accept': 'application/json'
};
function myCallbackFunction(data){
$('body').text(data.response);
}
$.ajax({
type: "GET",
headers : headers,
url: "https://site/api/etc",
dataType: "jsonp",
success: function(data){console.log(data);},
jsonp: false,
jsonpCallback : "myCallbackFunction",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
我明白了
error: Uncaught SyntaxError: Unexpected token :
我知道那是因为服务器 returns 有 json 数据,但我不知道如何更正它,因为如果将数据类型更改为 json 我会收到与 CORS 相关的错误:
XMLHttpRequest cannot load https://site/api/1.0/etc. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://site' is therefore not allowed access.
这意味着服务器端不支持 CORS
但我使用邮递员它有效我不明白。
我已经尝试了很多其他的东西,但可以得到数据。
请帮忙 。
谢谢你。
PS : 我在 tomcat 服务器下
我将把对我有用的东西放在这里:
所以我所做的是使用 "okhttp" 而不是 ajax 调用创建一个休息控制器,这样就不会有上下文创建问题然后检索数据并使用 js 操作它。
我正在尝试从不支持 CORS 的服务器获取 json 数据。我读到 Jsonp 是针对这种情况的解决方案,但我仍然无法使其工作: 我的代码:
var headers = {
'Authorization': 'Bearer ' + 'token',
'Accept': 'application/json'
};
function myCallbackFunction(data){
$('body').text(data.response);
}
$.ajax({
type: "GET",
headers : headers,
url: "https://site/api/etc",
dataType: "jsonp",
success: function(data){console.log(data);},
jsonp: false,
jsonpCallback : "myCallbackFunction",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
我明白了
error: Uncaught SyntaxError: Unexpected token :
我知道那是因为服务器 returns 有 json 数据,但我不知道如何更正它,因为如果将数据类型更改为 json 我会收到与 CORS 相关的错误:
XMLHttpRequest cannot load https://site/api/1.0/etc. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://site' is therefore not allowed access.
这意味着服务器端不支持 CORS 但我使用邮递员它有效我不明白。 我已经尝试了很多其他的东西,但可以得到数据。 请帮忙 。 谢谢你。 PS : 我在 tomcat 服务器下
我将把对我有用的东西放在这里: 所以我所做的是使用 "okhttp" 而不是 ajax 调用创建一个休息控制器,这样就不会有上下文创建问题然后检索数据并使用 js 操作它。