Angular CORS适用于GET,但不适用于DELETE

时间:2014-11-07 23:09:20

标签: java angularjs glassfish jax-rs cors

我有一个Angular应用程序进行交叉调用。所有GET调用都很有效。然而,DELETE调用抛出错误:

XMLHttpRequest cannot load http://my.url.com:8080/api/invoices/12768. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. 

在后端我正在使用带有Glassfish 4.1和Java 8的JAX-RS。我正在创建ResponseBuilder:

ResponseBuilder responseBuilder = Response
                    .status(status)
                    .type(MediaType.APPLICATION_JSON)
                    .header("Access-Control-Allow-Origin", "*")
                    .header("Access-Control-Allow-Credentials", "true")
                    .header("Access-Control-Allow-Methods", "POST, GET, DELETE")
                    .header("Access-Control-Max-Age", "1209600")
                    .allow("OPTIONS");

在Angular中我正在进行服务调用:

$http.delete(requestUrl)
                     .success(function (data, status, headers, config) {
                    deferred.resolve(data);
                }).error(function (data, status, headers, config) {
                    deferred.reject(status);
                });

问题是,这非常有效:

$http.get(requestUrl)
                     .success(function (data, status, headers, config) {
                    deferred.resolve(data);
                }).error(function (data, status, headers, config) {
                    deferred.reject(status);
                });

知道为什么GET会起作用,但不是DELETE?

编辑:

另外请注意,我知道它不是服务器端,因为如果我在本地计算机上通过Advanced Rest Client运行删除调用,则DELETE可以正常工作。

编辑2:

请求标题

User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) 
Chrome/{ipaddress} Safari/537.36
Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: treeForm_tree-hi=treeForm:tree:applications

回复标题

Server: GlassFish Server Open Source Edition 4.1 
X-Powered-By: Servlet/3.1 JSP/2.3 (GlassFish Server Open Source Edition 4.1 Java/Oracle Corporation/1.8)
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, GET, DELETE
Access-Control-Max-Age: 1209600
Allow: OPTIONS 
Content-Type: application/json 
Date: Fri, 07 Nov 2014 23:39:10 GMT 

内容长度:0

这些是来自高级休息客户端

的标题

1 个答案:

答案 0 :(得分:0)

好吧,显然Angular从标题中删除内容类型。使用它有效:

$http.delete({url:request,headers:{'Content-Type':'application/json'}})