Always got Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response
Asked Answered
G

2

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");
        });
Giulietta answered 2/4, 2016 at 14:3 Comment(2)
Have you registered the provider in your web.xml or application class?Octameter
I am using spring-boot and it works for other method like GET, POST. Only failed on DELETEGiulietta
G
42

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");
Giulietta answered 4/4, 2016 at 12:29 Comment(2)
Actually I ran into the same problem, but after taking a look into the documentation 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.Pomegranate
To be clear, this is added to the server-side code (for later readers of the answer).Tetrastichous
S
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

Snowshed answered 8/3, 2022 at 1:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.