1

I have a jersey web server add I want to make a post request from javascript:

    heartRateTimestamp = new Date().toISOString();
var client = new XMLHttpRequest();
var url = "http://192.168.0.226:8080/appdata/post";
console.log(url);
client.open("post", url);
client.setRequestHeader('Content-Type', 'application/json');
var parameters = [
    {
        "type": 2,
        "HeartRate": {
            "heartrate": 65,
            "heartratesTimestamp": heartRateTimestamp,
            "macAddress": "lsjfsf2s8vev8es"
        }
    }
];
client.send(JSON.stringify(parameters));
client.onload = function () {
    console.log(client.responseText);
    document.getElementById("response").innerHTML = "Messages: " + client.responseText;
}

When I try to do this I get an error:

XMLHttpRequest cannot load http://192.168.0.226:8080/appdata/post. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I think this a CORS problem so I followed this tutorial (http://www.codingpedia.org/ama/how-to-add-cors-support-on-the-server-side-in-java-with-jersey/) to overcome this but unfortunately I am still getting the same error. What could be the problem?

Jonathan Eustace
  • 2,469
  • 12
  • 31
  • 54
Tim
  • 445
  • 5
  • 19
  • Could you provide a snippet of what you used from the tutorial to implement the Cross Origin support? – Matthew Trout Apr 26 '16 at 11:49
  • The problem is that the response does not have the proper headers... something is not properly configured in the server side. You should add that code instead of the client code – Pablo Lozano Apr 26 '16 at 11:53
  • Which version from the tutorial did you use? Adding the headers to the resource method response, or in a filter? If you did the former, use the latter instead. Whoever wrote that article may not have tested the code. You should not add the headers in the resource method because the method would never get hit on the preflight, and the request would never do through. – Paul Samsotha Apr 26 '16 at 11:58
  • I used the 2.1. Response and ResponseBuilder section from the tutorial and I don't know if it matters but I put a string inside the entity instead of `podcastById, detailed ? new Annotation[]{PodcastDetailedView.Factory.get()} : new Annotation[0]` – Tim Apr 26 '16 at 12:07
  • 1
    That's what my comment was saying. Don't use that way. It will not work. Use the filter, also mentioned in the article – Paul Samsotha Apr 26 '16 at 12:11

0 Answers0