繁体   English   中英

带有Access-Control-Allow-Origin标头的Jquery + CORS +基本身份验证:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

[英]Jquery + CORS+ Basic Auth with Access-Control-Allow-Origin header: No 'Access-Control-Allow-Origin' header is present on the requested resource

我无法使用Basic Auth向使用jQuery的启用了CORS的Web服务器之一进行简单的GET请求。

该问题似乎与基本身份验证相关,因为当我在服务器上停用它时,请求可以正常工作 但是,启用基本身份验证后,它会失败, No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401

我添加了OPTIONS方法以返回带有4个标题的响应Access-Control-Allow-Origin: *Access-Control-Allow-Method: POST, GET, PUT, UPDATE, OPTIONSAccess-Control-Allow-Headers: Content-Type, Authorization, Accept, X-Requested-WithAccess-Control-Allow-Credentials:true

并在所有响应中添加了Access-Control-Allow-Origin: *标头。

我还尝试通过Postman发出OPTIONS请求,并且可以看到CORS标头:

Access-Control-Allow-Credentials → true Access-Control-Allow-Headers → Content-Type, Authorization, Accept, X-Requested-With Access-Control-Allow-Methods → POST, GET, PUT, UPDATE, OPTIONS Access-Control-Allow-Origin → *

我也尝试设置Access-Control-Allow-Origin: localhost:80而不是*但是结果是相同的。

我的JavaScript代码如下:

$.ajax({
url: this.host,
type: "GET",
data: {
    something: "something"
},
headers: {
    "Authorization": "Basic " + this.credentials,
    "Accept": "application/json"
},
cache: false
}).done(function (data, textStatus, xhr) {
}).fail(function (xhr, textStatus) {
})

我的服务器是一个简单的Java Web应用程序,Jersey运行在Tomcat7上。

我该如何解决这个问题?

谢谢!

尝试在beforeSend设置标题:

var that = this;
$.ajax({
  url: this.host,
  type: "GET",
  data: {
    something: "something"
  },
  beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Basic " + that.credentials);
  },
  cache: false
}).done(function (data, textStatus, xhr) {
}).fail(function (xhr, textStatus) {
});

Access-Control-Allow-Origin:*是您的问题。 进行身份验证的请求时,不能在此标头中使用通配符。 而是,将Access-Control-Allow-Origin显式设置为请求的Origin头中的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM