我需要訪問我的web api遠程託管我的反應的應用程序。在服務器端,我做了以下允許跨域通信:無法設置'訪問控制允許來源'標頭
import javax.ws.rs.core.Response;
import com.mypackage.ResponseDto;
@Override
public Response fetch(String id, String env) throws ServiceException
{
ResponseDto res = new ResponseDto();
res = updateResp(id, env); // not important
return Response.ok().header("Access-Control-Allow-Origin","*").entity(res).build();
}
,當我從郵遞員檢查,我可以看到CORS標頭正確設置如下:
access-control-allow-origin →*
content-type →application/json
date →Wed, 16 Aug 2017 11:07:16 GMT
server →web
transfer-encoding →chunked
但是,當我從訪問相同的端點反應過來的應用程序,瀏覽器開始與以下錯誤提示:
Fetch API cannot load http://myservices.com/myservice-app/services/ . 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:3000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
任何想法什麼回事?
編輯#1 下面有沒有變化仍然出現相同的錯誤:
return Response.ok()
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "POST, GET, PUT, UPDATE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With")
.entity(response).build();
標題需要被添加到OPTIONS請求的響應中(這是瀏覽器發送的'預檢'請求),而不是(僅)GET或POST。也許這就是問題所在? –
服務器的響應如何,當它收到一個OPTIONS請求,這是在下一個請求之前發送的 – Ferrybig
[「No'Access-Control-Allow-Origin'標頭存在於請求的資源中]」( https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource) – Ferrybig