28

I am using jersey as my restful api implementation. In the front end, I am using angularjs $http service to make http request. When I request a delete method I always got below error.

"Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response."  

I read some articles and they say I need to allow delete on "Access-Control-Allow-Methods". I have setup the response filter as below but it still has such problem. What else should I do?

@Provider
public class CORSResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");
        headers.add("Access-Control-Allow-Methods", "*");
    }
}

below is my angular code to make the request:

$http({
            method: 'DELETE',
            url: remoteUrl,
            headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
                'ACCESS_TOKEN' : $cookieStore.get("access_token")
            },
            data : $httpParamSerializer({
                'id':id
            })
        }).success(function(data,status,headers,config) {
            $scope.refreshDepartments();
            console.log(data);
            alert("success");
        }).error(function(data,status,headers,config){
            console.log(data);
            alert("error");
        });
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

2 Answers2

40

After some testing, I found the solution. I put the allow method on the header as below, then it works. I don't know why "*" doesn't work.

headers.add("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, DELETE");
Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • Actually I ran into the same problem, but after taking a look into the documentation https://www.w3.org/TR/cors/#access-control-allow-methods-response-header I don't know how I could think that "*" could work for the allow-methods header. – JepZ Jan 14 '17 at 01:54
  • 1
    To be clear, this is added to the *server-side code* (for later readers of the answer). – Heretic Monkey Jan 06 '20 at 20:55
3

The value " * " only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal method name "*" without special semantics.

Source : https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

kaizoku
  • 31
  • 1