簡體   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