简体   繁体   中英

403 Status (Forbidden) when PUT and DELETE using AJAX

I've implemented a small REST API using JAX-RS (Jersey 2.0) and I'm using AJAX to call the API, GET and POST work fine but when I get to call any PUT or DELETE methods, all I get is the following error message:

Failed to load resource: the server responded with a status of 403 (Forbidden)

Here's an example of a DELETE method in Java:

    @Path("/deleteSomething")
    @DELETE
    @Consumes("application/json")
    public void delete(String json) throws ParseException {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse( json );
        JSONObject object=(JSONObject)obj;

        String id = (String) object.get("id");
        System.out.println("ID  :   " + id);
        //DO SOMETHING HERE
    }

And here is the Javascript call using AJAX:

function deleteSomethingAjax() {
    $.ajax({
        url: API_URI + "/deleteSomething", //API_URI is the API's uri
        contentType : 'application/json',
        data: idToJSON(), // this function just returns a JSON obj {"id":"myID"}
        type:  'DELETE',
        success : function(data, textStatus, jqXHR) {
            alert( "Fine!" );
        },

        error : function(jqXHR, data, textStatus, errorThrown) {
            alert('WOOPS, something wrent wrong...');
        }
    });
}

Any help will be much appreciated!! Thank you!!

The issue had to do with the CORSFilter set-up, I was setting it wrong in the web.xml file. Here is the part of the CORSFilter, well set inside web.xml :

<filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM