首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用JAX-RS/RESTEasy实现CORS的Ajax请求

使用JAX-RS/RESTEasy实现CORS的Ajax请求
EN

Stack Overflow用户
提问于 2013-01-30 01:47:50
回答 5查看 17K关注 0票数 5

我有两个服务器(Apache和JBoss AS7),我需要向客户端提供对所有http方法的访问。所有这些请求都必须通过ajax发送。客户端代码示例:

代码语言:javascript
运行
复制
$.ajax({
      type: "get",
      url: "http://localhost:9080/myproject/services/mobile/list",
      crossDomain: true,
      cache: false,
      dataType: "json",
      success: function(response) {
        console.log(response);
      },
      error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(jqXHR.responseText);
        console.log(errorThrown);
        }
    });

在JBoss AS7中,我使用RESTEasy实现CORS,如下所示:

代码语言:javascript
运行
复制
@Path("/mobile")
@Provider
@ServerInterceptor
public class GroupMobile implements MessageBodyWriterInterceptor {

@Inject
private GroupDAO groupDAO;

@GET
@Path("/list")
@Produces(MediaType.APPLICATION_JSON)
public List<Group> getGroups() {
    return groupDAO.listAll();
}

@Override
public void write(MessageBodyWriterContext context) throws IOException,
        WebApplicationException {
    context.getHeaders().add("Access-Control-Allow-Origin", "*");
    context.proceed();
}

@OPTIONS
@Path("/{path:.*}")
public Response handleCORSRequest(
        @HeaderParam("Access-Control-Request-Method") final String requestMethod,
        @HeaderParam("Access-Control-Request-Headers") final String requestHeaders) {
    final ResponseBuilder retValue = Response.ok();

    if (requestHeaders != null)
        retValue.header("Access-Control-Allow-Headers", requestHeaders);

    if (requestMethod != null)
        retValue.header("Access-Control-Allow-Methods", requestMethod);

    retValue.header("Access-Control-Allow-Origin", "*");

    return retValue.build();
}
}

web.xml和beans.xml是空文件。当我访问MyIP:8080 (Apache)时,我收到错误消息:

代码语言:javascript
运行
复制
XMLHttpRequest cannot load http://localhost:9080/myproject/services/mobile/list?_=1359480354190. Origin http://MyIP:8080 is not allowed by Access-Control-Allow-Origin.

有人知道哪里出了问题吗?

EN

Stack Overflow用户

发布于 2013-12-26 21:20:16

听起来这个问题跟https://issues.jboss.org/browse/RESTEASY-878有关。您可能无法使用MessageBodyWriterInterceptor捕获CORS印前检查请求。请尝试使用servlet过滤器(@WebFilter)。

票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14589031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档