问题描述
我使用JAX-RS(Jersey 2.0)实现了一个小型REST API,我使用AJAX来调用API,GET和POST工作正常但是当我调用任何PUT或DELETE方法时,我得到的只是是以下错误消息:
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:
无法加载资源:服务器响应状态为403(禁止)
以下是Java中 DELETE 方法的示例:
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
}
这里是Javascript调用AJAX:
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!!
推荐答案
这个问题与CORSFilter设置有关,我在 web.xml 文件。以下是CORSFilter的一部分,设置在 web.xml 内:
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>
这篇关于403使用AJAX进行PUT和DELETE时的状态(禁止)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!