![](/img/trans.png)
[英]XMLHttpRequest 'Access-Control-Allow-Origin' Error
[英]Error with 'Access-Control-Allow-Origin'
我有一個用angular 2創建的網頁,該網頁是一種表單,在表單結尾必須將表單發送到我的java服務器。 但是我無法發送,出現錯誤Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
我已經更改了服務器,因此它將發送Access-Control-Allow
標頭。 函數是這樣的:
public static Response buildResponse(int status, Object reponseObject, MediaType mediaType) {
Response.ResponseBuilder rb = Response.status(status).entity(reponseObject);
if (mediaType != null) {
rb = rb.type(mediaType);
}
rb = rb.header("Access-Control-Allow-Origin", "*");
rb = rb.header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
rb = rb.header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token, accept");
rb = rb.header("Access-Control-Allow-Credentials", true);
System.out.println("teste");
return rb.build();
}
我也嘗試將標頭'Access-Control-Request-Method': 'POST'
到頁面請求中,但是仍然出現錯誤。 問題不在於軟件功能本身,因為如果我安裝並激活chrome的CORS插件,它就可以正常工作,但是我不能要求用戶安裝該插件以使用我的網站。 有誰知道我在想什么? 我已經搜尋了一段時間,我發現的唯一解決方案是禁用此瀏覽器安全性(我不能要求用戶這樣做),並在請求中添加標頭,這是我已經擁有的。
我終於能夠解決我的問題。 問題出在我的頁面和服務器之間的通信中。 CORS塊是由瀏覽器強加的,服務器需要發送用於授權訪問的標頭(我在問題中的函數中添加的標頭)。 我所缺少的是OPTION
方法中的標頭。 我的JavaScript代碼會在實際的GET
或POST
方法之前自動發送和OPTIONS
請求( preflight request
)。 我所做的是在服務器上手動實現OPTIONS
方法,以響應必要的標頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.