我想访问从 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 库:
过滤器-1.9.2.jar
java-property-utils-1.9.jar
我已经在互联网上阅读了这个问题,但仍然无法解决
拜托,我能帮我吗?谢谢!!
是的,我找到了解决方案。问题出在错误 500 内部服务器中,它向我表明请求发送的参数未到达服务。与 NULL 相同。我修改服务以接收 GET 并且它有效!