我有一个Apache Tomcat / 8.5.11服务器和jQuery ajax请求它。当我试图从浏览器(在一个域中)向服务器(在另一个域)发送一些请求时,我发现了CORS并通过这种方式解决了问题:
添加到web.xml:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,
X-Requested-With,accept,
Origin,Access-Control-Request-Method,
Access-Control-Request-Headers, authorization, Authorization, accept, Accept</param-value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这个ajax开始起作用了:
$.ajax({
type: 'POST',
url: 'http://185.18.52.203:8080/registration',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({"num": "123"}),
error: function(jqXHR, textStatus, errorThrown) {$("p").text(textStatus);},
success: function(data){$("p").text(data);}
});
但是当我尝试用Base Auth
做同样的事情时
$.ajax({
type: 'POST',
url: '//185.18.52.203:8080/create',
contentType: 'application/json',
//xhrFields: {withCredentials: true},
xhrFields: {
withCredentials: true
},
dataType: 'json',
//headers: {
//"Authorization ": "Basic MTp5ZW5vdA==",
//"Access-Control-Allow-Origin: ": "*",
//"Access-Control-Allow-Methods: ": "POST",
//"Access-Control-Allow-Headers: ": "Authorization",
//"Authorization": 'Basic MTp5ZW5vdA==',
//},
//crossDomain: true,
data: JSON.stringify({...}),
beforeSend: function(xhr) {
//xhr.withCredentials = true;
xhr.setRequestHeader ("Authorization", "Basic MMt7DZ5vdA==");
//xhr.setRequestHeader("Access-Control-Allow-Methods:", "POST");
//xhr.setRequestHeader("Access-Control-Allow-Headers: ", "*");
},
error: function(jqXHR, textStatus, errorThrown) {$("p").text(textStatus);},
success: function(data){$("p").text(data);}
});
我有错误:
XMLHttpRequest无法加载http://185.18.52.203:8080/ ...响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许来源“http://192.168.0.105” 访问。响应的HTTP状态代码为401.
我保存我的评论只是因为理解我尝试过很多事情 感谢