我嘗試訪問Rest服務,該服務通過ajax調用託管在我的不同域中,並且在螢火蟲中出現「CORS」錯誤。即使在服務中添加Access-Control-Allow-Origin後,CORS也無法修復
在研究了這個問題後,我發現需要通過在響應頭中添加Access-Control-Allow-Origin來*來改變服務。我在服務中也這樣做了。
public Response search(String expression) {
return Response.ok() //200
.entity(ConnectionUtils.query(expression))
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
.header("Access-Control-Allow-Headers", "Content-Type,Accept")
.allow("OPTIONS").build();
}
上述方法實現類的以下服務接口:
@POST
@Path("/search")
public Response search(String expression);
我試圖通過先進的鉻其餘客戶端發佈到這個URL的請求,我得到的響應爲好。此外,響應標頭還顯示Access-Control-Allow-Origin也已正確設置。請參考下面的Chrome用戶端的截圖:
如果你看到上面的響應頭已經被改變。
但我下面的Ajax調用總是返回CORS錯誤:
" Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.1.100:8080/cqs-1.0-SNAPSHOT/services/services/cqs/search. This can be fixed by moving the resource to the same domain or enabling CORS."
$.ajax({
type: 'POST',
url: "http://192.168.1.100:8080/cqs-1.0-SNAPSHOT/services/services/cqs/search",
crossDomain: true,
dataType: 'json',
data: {"offer.offer.offerId.USSellerId": {$gt: 0}},
headers: {
"Accept": "application/json",
contentType: "application/json"
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data.statusText);
console.log(data.name);
}
});