考虑以下头部信息:
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic TWluZVN0YXI6TWluZVN0YXI=
Cache-Control:max-age=0
Connection:keep-alive
Host:*
这个头信息是针对URL的。我正在尝试从这个URL中获取JSON值。访问这个URL时,会弹出一个要求输入用户名和密码的界面。 尝试1:
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/*/*',
dataType:"json",
username: '*',
password: '*',
async: false
}).responseText;
TRY2
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/jolokia/*/*',
dataType:"json",
crossDomain: true,
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa('*' + ":" + '*'));
},
async: false
}).responseText;
尝试3:
尝试在Tomcat的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</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</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param- value>
</init-param>
<init-param>
<param-name>cors.support.credentials</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cors.preflight.maxage</param-name>
<param-value>10</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但我仍然无法访问该网址,仍然会出现以下错误:
GET http://***.**.**.**:9898/*/* 401 (Unauthorized)
jquery.min.js:5 XMLHttpRequest cannot load http://**.**.**.**:9898/*/*. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin http://localhost:8080 is therefore not allowed access. The response had HTTP status code 401.(index):1 Uncaught SyntaxError: Unexpected token u
我只需要访问该URL并从该URL获取JSON值。该URL受用户名和密码保护,我知道。
我不知道这是否会是跨域问题。当我从URL中删除身份验证时,此代码正常工作:
$.ajax({
type:'GET',
url: 'http://'+domainName+':9898/*/*',
dataType:"json",
async: false
}).responseText;
但是一旦我验证了URL,代码就会失败,在执行以上步骤后,代码仍然无法正常运行。
xhrFields: { withCredentials: true }
很神奇。 - Nagendra Singh