当前位置: 首页 > 知识库问答 >
问题:

如何消除基于java的Web服务服务器中请求的资源错误中没有Access-Control-Allow-Origin头

周辉
2023-03-14

我试图构建一个webservice(基于Java的服务器和基于Javascript的客户机),我只需要发送一个带有json数据的Post请求,我需要从服务器得到一个带有json数据的Post响应。到目前为止,我已经实现了这些:(我的客户端实现与html5 rocs教程几乎相同)

Web服务客户端(js):

    // I call client = new WSclient() in one of my js files   
    WSclient=function(){
      makeCorsRequest();
    }

    // Create the XHR object.
    function createCORSRequest(method, url) {
      var xhr = new XMLHttpRequest();
      if ("withCredentials" in xhr) {
        // XHR for Chrome/Firefox/Opera/Safari.
        xhr.open(method, url, true);
      } else if (typeof XDomainRequest != "undefined") {
        // XDomainRequest for IE.
        xhr = new XDomainRequest();
        xhr.open(method, url);
      } else {
        // CORS not supported.
        xhr = null;
      }
      return xhr;
    }

    // Helper method to parse the title tag from the response.
    function getTitle(text) {
      return text;
    }

    // Make the actual CORS request.
    function makeCorsRequest() {
      // All HTML5 Rocks properties support CORS.
      var url = 'http://localhost:8080/myapp/myfunction';
      var xhr = createCORSRequest('POST', url);
      xhr.setRequestHeader(
          'X-Custom-Header', 'value');
      xhr.send();
    }

Web服务服务器(java)

@Path("/myapp/")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class myFunctionClass {


    @POST
    @Path("myfunction")
    public Response recommendations(User inf){
        // From the client I also need to send json 
        // like {"name":"john","surname":"smith","name":"marry","surname":"smith"}
        // and if possible I want to put this infformation inside inf object
        List<String> infos = inf.getInformation();

         // here I call one of the my methods to get recommendations
         // I remove it for simplicity and just put type of recommendations object 
         // list<Recommendation> recommendations= runFunction(infos);

        final StringWriter sw =new StringWriter();
        final ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(sw, recommendations);
        System.out.println(sw.toString());
        sw.close(); 


        return Response.ok(sw.toString(), MediaType.APPLICATION_JSON).header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "POST").allow("OPTIONS").build();


    }
}
    XMLHttpRequest cannot load      http://localhost:8080/myapp/myfunction. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.

编辑

当我移除

 xhr.setRequestHeader(
              'X-Custom-Header', 'value');  

从客户端来说,它工作正常。正如我之前所说,这是我第一次使用Web服务和javascript,所以实际上我不知道这行代码是做什么的。谁能解释一下它存在与否会发生什么?

xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

共有1个答案

谭桐
2023-03-14

发生的情况是,在初始请求之前发出了一个飞行前请求(它是options请求)。因此,您需要一个@optionsendpoint来处理该请求(即设置响应头)。在当前代码中,您试图在原始请求的endpoint响应中设置它,而OPTIONS请求甚至无法到达该endpoint响应。

一种更常见的方法,不是为每个目标创建@optionsendpoint,而是使用Jersey过滤器,如本答案所示。所有请求的头都将被发送出去。

另见:

    null
@OPTIONS
@Path("myfunction")
public Response cors() {
    return Response.ok()
        .header("Access-Control-Allow-Origin", "*")
        .header("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS, HEAD")
        // whatever other CORS headers
        .build();
}
 类似资料:
  • 我知道这件事以前被处理过很多次。但是我可以在响应中看到头上已经有了Access-Control-Allow-Origin。 accept:/ accept-encoding:gzip,deflate,sdch,br access-control-request-headers:x-an-webservice-identitykey access-control-request-method:pos

  • 我正在尝试获取一个新闻网站的提要。我想我应该使用Google的feed API将feedburner提要转换为JSON。下面的url将以json格式从提要返回10个帖子。http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&q=http://feeds.feedburner.com/Mathrubhumi 我使用下面的代码来

  • 问题内容: 我想访问来自同一域但端口号不同的信息,为此,我添加了响应头。 Servlet代码:( 显示在www.example.com:PORT_NUMBER上) jQuery代码:( 显示在www.example.com上) 几次我收到此错误(在控制台中): 该错误通常在执行时首次发生。第二次允许。 我的问题是代码中或代码中缺少什么? 任何建议将不胜感激。 更新1 我变了: 至: 然后我在控制台

  • 我在前端使用Angular,在后端使用Java Spring,但是我得到了错误:,而我确信CORS是启用的。这是我的配置文件: 它工作了,我可以毫无问题地完成所有其他请求,但服务中的这个PUT请求给了我一个错误: 这是我的服务器端:

  • 问题内容: 到目前为止,我想出了下面的代码,它是读取xml的非常基本的代码,但是出现以下错误。 XMLHttpRequest无法加载****。所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访问源’ http://run.jsbin.com ‘。 我没有发现我的代码有什么问题,所以我希望有人可以指出我的代码有什么问题以及如何解决。 问题答案: 由于

  • 我有一个网络服务,比如: 在链接中: 我正在尝试通过链接中的AlFresco获取此Web服务的响应:。我现在有不同的端口(当我有相同的端口时,这很好地工作),所以,使用不同的端口,我在AlFresco中得到错误: 跨源请求被阻止:同一源策略不允许在以下位置读取远程资源:http://localhost:8081/ChangesPDF/Changes?...(原因:缺少CORS的“访问控制允许原点”