Grizzly服务器在localhost:8080上运行,它使用Jersey提供REST接口。
CorsFilter类负责创建CORS头。它被添加到GrizzlyServer的资源配置中:
final ResourceConfig rc = new ResourceConfig()
.packages("my.application.api.rest")
.register(new CorsFilter());
GrizzlyHttpServerFactory.createHttpServer(uri, rc); // uri defined earlier
以下是另一篇文章中的CorsFilter类:
@Provider
public class CorsFilter implements ContainerResponseFilter {
private final String HEADERS = "Origin, Content-Type, Accept";
@Override
public void filter(ContainerRequestContext request, ContainerResponseContext response) throws IOException {
response.getHeaders().add("Access-Control-Allow-Origin", "*");
response.getHeaders().add("Access-Control-Allow-Headers", HEADERS);
response.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
}
}
有两个代表REST处理程序的类: my.application.api.rest.A.class my.application.api.rest.B.class
资源A和B都有POST处理程序:
@Path("/A")
public class A {
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response handlePost()
{
Object payload = getPayload();
return Response.ok(payload).build();
}
}
B看起来与A相似。
客户端是一个基于AngularJS的Web应用程序,托管在localhost:3000的本地节点服务器上。使用Restangular:
完成对/ A和/ B的POSTRestangular.all('A').post({
key: value
});
虽然所有可用的浏览器(Chrome,Safari,Firefox)都会执行POST到A,但由于以下错误,不会执行与B相同的POST:
XMLHttpRequest cannot load http://localhost:8080/myapplication/B. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 500.
我认为CorsFilter添加的标题在某处丢失了。
Postman到A和B的POST工作得很好,标题" Access-Control-Allow-Origin:*"永远存在。