Response to preflight request doesn't pass acc

2019-09-04 14:49发布

问题:

I Am not able to fetch data from Rest Server.Following Error is coming: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."

Response is coming as "0", This is not hitting the Rest Method also.

Rest APT:

@POST
    @Timed
    @Path("updateScore")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response updateScore(Player player)
    {
    StringBuilder returnStr = new StringBuilder("Sucess");
    return Response.ok().
            header("Access-Control-Allow-Origin", "http://localhost:8080").
            header("Access-Control-Allow-Methods",  "GET, POST, PATCH, PUT, DELETE, OPTIONS").
            header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token").
            allow("OPTIONS").
            status(200).
            entity("Hello").build();
}

JavaScript Call

    var url = "http://192.168.0.101:9090/api/FGame/updateScore/";
            var client = new XMLHttpRequest();
            client.open('POST', url, true);
            client.setRequestHeader('Content-Type', 'application/json');
            client.send('{"Name" : 12}');
            client.onreadystatechange = function() {
                   alert(client.status);
                   alert(client.data)
            };

But if I am changing to JavaScript call as following then working fine. JavaScript Call

    var url = "http://192.168.0.101:9090/api/FGame/updateScore/";
            var client = new XMLHttpRequest();
            client.open('POST', url, true);
            client.send(null);
            client.onreadystatechange = function() {
                   alert(client.status);
                   alert(client.data)
            };