我想访问从AJAX查询的服务,但是当我调用此服务时,在控制台浏览器中显示以下内容:
XMLHttpRequest cannot load http://192.168.108.166:8080/LdapRESTEasy/rest/RESTEasyLdap/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
我正在使用Apache Tomcat 6并创建一个服务,当我登录时,RESTeasy会返回带有用户数据的JSON。
我的包含AJAX的javascript代码如下:
function login(){
var hashNoEnconding = document.getElementById("user").value +'|'+ document.getElementById("pass").value;
var hashEnconding = base64Encode(hashNoEnconding);
var url = "http://192.168.108.166:8080/LdapRESTEasy/rest/RESTEasyLdap/login";
$.ajax({
url:url,
type:'POST',
encoding:"UTF-8",
headers: {
"Content-Type":"application/json; charset=UTF-8"
},
contentType: "application/json; charset=UTF-8",
accept: "application/json; charset=UTF-8",
cacheControl: "no-cache",
beforeSend: function (request){
request.setRequestHeader("authorization", hashEnconding);
},
success:function (data, status, xhr) {
},
error: function (data) {
}
});
}
从apache tomcat服务器配置web.xml,建议添加CORS过滤器
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Content-Type, X-Requested-With, Accept, Authentication, Authorization</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我还在/ lib中添加了apache库:
CORS滤波器-1.9.2.jar
java的属性-utils的-1.9.jar
我已经在网上看过这个问题,但仍然无法解决
拜托,我能帮帮我吗? 谢谢!
答案 0 :(得分:0)