【发布时间】:2013-04-10 18:40:25
【问题描述】:
我正在尝试发出跨域请求。我知道 CORS 并想测试来自例如 w3schools 的呼叫作为域。
我将 Jersey 用于 REST API 和 Apache 服务器,并执行了以下操作:
ResponseBuilder rb = Response.status(status).entity(mapper.writeValueAsBytes(data)).type(MediaType.APPLICATION_JSON);
**EDITED **
rb.header("Access-Control-Allow-Origin","*");
rb.header("Access-Control-Allow-Methods","GET, OPTIONS");
rb.header("Access-Control-Allow-Headers","*");
return rb.build
当我从浏览器调用我的 API 查看我的响应标头时,我看到了
访问控制允许标题:*
访问控制允许方法:GET、OPTIONS
访问控制允许来源:*
缓存控制:私有
内容长度:2523
内容类型:应用程序/json
日期:格林威治标准时间 2013 年 4 月 17 日星期三 20:16:20
过期:周三,1969 年 12 月 31 日 16:00:00 PST
服务器:Apache-Coyote/1.1
但是当我想使用不同的域(即在 W3 学校)真正测试它时,我有以下内容 -
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "url", // this is a real URL replaced with just url
type: 'GET',
success: function(content) { console.log("ok"); },
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("error");
},
complete: function() { console.log("complete"); }
});
});
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
我总是收到无法加载的 XMLHttpRequest :url:。 Access-Control-Allow-Origin 不允许来源http://www.w3schools.com。
我的请求标头是
接受:*/*
来源:http://www.w3schools.com
推荐人:http://www.w3schools.com/jquery/tryit_view.asp?x=0.8691769954748452
用户代理:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
我也尝试在 jsfiddle 中测试上述内容,但得到了同样的错误。
注意:我的 URL 仍然在我的本地主机上,这可能是问题吗?
我错过了什么?
【问题讨论】:
-
您也可以分享请求标头吗?我的猜测是您将需要一个
Access-Control-Allow-Headers标头,或者您将需要处理 OPTIONS 请求。另请注意,您的响应标头显示Allow-Control-Allow-Methods,它应该是Access-Control-Allow-Methods -
@anazimok :通过转到该 URL,我能够导航到 enable-cors.org/server_apache.html ,它告诉我应用似乎已应用的标题?我还有什么遗漏的吗?
-
@monsur :我已经用请求标头更新了我的问题。我现在就试试你的建议,让你知道
-
@Rahul:你确定 w3schools.com 支持 CORS 吗?我试过点击我知道的网站支持来自 jquery 的 cors,它工作得很好,而 w3schools.com 不支持。请参阅此处的示例:jsfiddle.net/anazimok/3J2F6