我正在尝试在DropWizard (version 0.7)上启用CORS
// Enable CORS headers
final FilterRegistration.Dynamic cors =
env.servlets().addFilter("CORS", CrossOriginFilter.class);
// Configure CORS parameters
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
cors.setInitParameter("allowedHeaders",
"Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
cors.setInitParameter("allowCredentials", "true");
// Add URL mapping
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
我在run方法中添加了这个代码片段。
@POST
@Path(value = "/match")
@Produces(MediaType.APPLICATION_JSON)
public Response match(){
}
这是我通过JQuery Ajax调用的REST方法
$.ajax({
headers: {
'Content-Type': 'application/json'
},
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Accept","application/json");
},
async: true,
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:1111/service/matchdevice",
data: "{"input":"test"}",
success: function (result) {
console.log("success");
},
error: function(reserr){
console.log(reserr);
}
})这是我的JQuery ajax调用。当我发送它时,我得到了这个错误。
OPTIONS http://localhost:1111/service/match 400(错误请求)send @ jquery.min.js:4m.extend。Ajax @ jquery.min.js:4(匿名函数)@(索引):24(index):1 XMLHttpRequest无法加载http://localhost:1111/service/match预飞行响应的HTTP状态码400无效
我搜索了一下,没有找到任何解决这个错误的方法。
使用不同的过滤器成功启用CORS。
com.thetransactioncompany.cors.CORSFilter
代码范例import com.thetransactioncompany.cors.CORSFilter;
class Service{
public static final String CORSFILTER = "CORS";
private static final String CORS_SUPPORTED_METHODS = "cors.supportedMethods";
private static final String CORS_SUPPORTS_CREDENTIALS = "cors.supportsCredentials";
private static final String CORS_EXPOSED_HEADERS = "cors.exposedHeaders";
private static final String CORS_SUPPORTED_HEADERS = "cors.supportedHeaders";
private static final String CORS_ALLOW_ORIGIN = "cors.allowOrigin";
@Override
public void run(final Configuration conf, final Environment env) throws Exception {
final FilterRegistration.Dynamic filter = env.servlets().addFilter(CORSFILTER, CORSFilter.class);
filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, env.getApplicationContext().getContextPath() + "*");
filter.setInitParameter(CORS_ALLOW_ORIGIN, appConfigs.getAllowOrigin());
filter.setInitParameter(CORS_SUPPORTED_HEADERS, appConfigs.getSupportedHeaders());
filter.setInitParameter(CORS_EXPOSED_HEADERS, appConfigs.getExposedHeaders());
filter.setInitParameter(CORS_SUPPORTS_CREDENTIALS, appConfigs.getSupportsCredentials());
filter.setInitParameter(CORS_SUPPORTED_METHODS, appConfigs.getSupportedMethods());
}
}