即使所有 CORS headers 都存在,跨源资源共享问题

Cross Origin Resource sharing issue even when all the CORS headers are present

尽管我已经在我的服务响应中附加了以下提供的 CORS Headers :

resp.setContentType("application/json");
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Credentials", "true");
resp.addHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
resp.addHeader("Access-Control-Allow-Headers", "Origin,accept,content-type");
resp.flushBuffer();

我在尝试通过我的 AngularJS 前端访问服务中的某些 POST Web 方法时,仍然在控制台中遇到以下错误。

XMLHttpRequest cannot load http://192.***.*.***:8080/abc/def/search/vehicleManufacturer. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.***.*.***:8085' is therefore not allowed access.

然而,在同一个 class 中,某些 POST 方法没有任何有效负载,但响应完美。有什么建议吗?

编辑---------->

下面是我的 AngularJS 调用 web 方法的客户端屏幕代码:-

getVehicleModel : function(searchData,$scope){
     $http({
         method:'POST',
         url:'http://192.169.*.***:8085/abc/def/search/vehicleModel',
         dataType:'jsonp',
         data:searchData

     }).
     success(function(data){
         console.log("vehicle model")
         $scope.vehicleModel = data.Response;

     });


},

我认为这里的问题是 Preflighted Requests 在 CORS 中。

来自 Mozilla 文档,

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

  • It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than

    • application/x-www-form-urlencoded,
    • multipart/form-data
    • text/plain

    e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.

  • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

如上所述,即使您发出的是一个简单的 POST 请求,您请求中的 Content-Type 是 application/json,这与上面提到的 3 种类型不同,所以它被视为预检请求,并且在您实际 POST 请求之前触发 OPTIONS 请求。

您可以通过在您的 servlet 中实现 doOptions 来解决这个问题,只需在其中添加 headers 即可:)

由于您正在发送 cross-origin ajax 请求并使用此 GET 请求指定授权 header,因此正在进行预检(OPTIONS)。

另外(这不会引起问题)我建议删除 contentType 选项。这在 GET 请求的上下文中没有意义。 GET 请求不应包含任何内容。所有数据都应包含在查询字符串中,或​​者可能 headers.

授权 header 将不会与 OPTIONS 一起发送。你必须承认它 server-side,然后浏览器将发送底层 GET。在 https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS 阅读更多关于 CORS 的信息。