如何用Javascript、jQuery实现CORS

How implements CORS with Javascript, jQuery?

本文关键字:实现 CORS jQuery 何用 Javascript      更新时间:2023-09-26

我在使用rest服务时遇到了问题。已经在我的Java应用程序中实现了CORS过滤器,但是当我使用$.ajax()时,它返回CORS问题。使用$.getJSON可以访问该方法,但是我不能在其上添加头。

我需要知道如何在$.getJSON中添加标题或如何使其识别我在Java服务中添加的CORS。

我正在使用Java 8, Wildfly 8.1-Final, RestEasy等

我的ajax像这样:

var url = "http://pacoteiro-trysoft.rhcloud.com/api/v1/pacote/RC824435750CN";
$.ajax({
    async : true,
    type:'GET',
    contentType: 'application/json',
    url: url,
    cache:false,
    dataType: 'json',
    headers: {
        "token":"123"
    },
    success: function(data) { 
        alert("Cadastrado com sucesso!", data);
    },

 error: function(data) {
        alert("Erro!", data);
    }
});

和我的过滤器:

@Provider
public class ConfigureCORSFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext,ContainerResponseContext responseContext) throws IOException {
          responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
          responseContext.getHeaders().add("Access-Control-Allow-Headers", "application/json, origin, content-type, accept, authorization");
          responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
          responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
          responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
    }
}

在ajax请求中,您可以使用crossDomain选项来启用CORS

$.ajax({
    async : true,
    type:'GET',
    contentType: 'application/json',
    url: url,
    cache:false,
    dataType: 'json',
    crossDomain:true,
    headers: {
        "token":"123"
    },
    success: function(data) { 
        alert("Cadastrado com sucesso!", data);
    },

 error: function(data) {
        alert("Erro!", data);
    }
});

如果你在目录系统上工作,那么你需要禁用chrome安全并允许在本地系统上进行CORS验证。要做到这一点,进入你的chrome.exe文件夹(我在这里说的是windows),并执行以下命令:

chrome.exe --disable-web-security

解决这个问题的方法是添加单词标记:

  responseContext.getHeaders().add("Access-Control-Allow-Headers", "token, origin, content-type, accept, authorization");

CORS在我的filter在Java,因为我在headers AJAX中使用它。完整的解决方案如下:

@Provider
public class ConfigureCORSFilter implements ContainerResponseFilter {
    @Override
    public void filter(ContainerRequestContext requestContext,ContainerResponseContext responseContext) throws IOException {
          responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
          responseContext.getHeaders().add("Access-Control-Allow-Headers", "token, origin, content-type, accept, authorization");
          responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
          responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
          responseContext.getHeaders().add("Access-Control-Max-Age", "1209600");
    }
}