加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:54:47 所属栏目:百科 来源:网络整理
导读:我有两个服务器(Apache和JBoss AS7),我需要提供对客户端的所有http方法的访问.所有这些请求必须通过ajax发送. 客户端代码示例: $.ajax({ type: "get",url: "http://localhost:9080/myproject/services/mobile/list",crossDomain: true,cache: false,dataTyp
我有两个服务器(Apache和JBoss AS7),我需要提供对客户端的所有http方法的访问.所有这些请求必须通过ajax发送.
客户端代码示例:
$.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:

@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)时,收到错误消息:

XMLHttpRequest cannot load http://localhost:9080/myproject/services/mobile/list?_=1359480354190. Origin http://MyIP:8080 is not allowed by Access-Control-Allow-Origin.

有人知道出了什么问题吗?

解决方法

您遇到的问题是您正在尝试跨站点脚本.您访问了http:// MyIP:8080页面,因此浏览器阻止您访问该域外的资源.这是非常特定于浏览器的,基于浏览器的解决方案都会有所不同(您可以在Chrome中全局禁用安全性,在IE中基于每个站点禁用安全性).

如果您将页面加载为http:// localhost:8080,则应该允许您访问该查询.或者,您可以实现转发请求的代理.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读