更新时间:2023-11-19 17:30:46
这里的错误是过滤器尚未通过 addMappingForUrlPatterns
方法配置URL路径。
The bug here is that the filter hasn't been configured with a URL path via the addMappingForUrlPatterns
method.
这对我来说使用了dropwizard 0.7 .1:
This worked for me using dropwizard 0.7.1:
import org.eclipse.jetty.servlets.CrossOriginFilter;
import javax.servlet.DispatcherType;
import java.util.EnumSet;
public void run(Configuration conf, Environment environment) {
// Enable CORS headers
final FilterRegistration.Dynamic cors =
environment.servlets().addFilter("CORS", CrossOriginFilter.class);
// Configure CORS parameters
cors.setInitParameter("allowedOrigins", "*");
cors.setInitParameter("allowedHeaders", "X-Requested-With,Content-Type,Accept,Origin");
cors.setInitParameter("allowedMethods", "OPTIONS,GET,PUT,POST,DELETE,HEAD");
// Add URL mapping
cors.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
我假设你在浏览器中测试这个,但是你可以通过CLI验证如下curl命令:
I'm assuming you're testing this live in a browser, but you can verify via CLI with a curl command like this:
$ curl -H "Origin: http://example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: X-Requested-With" \
-X OPTIONS --verbose \
http://localhost:8080
你应该看到一个一堆访问控制 - *
响应中的HTTP标头。
You should see a bunch of Access-Control-*
HTTP headers in the response.