I am using Java 8, Tomcat 8, Spring 3.0, jQuery 2.2.4, chrome browser.
My request using $.ajax is successful. I am moving away from jQuery and wanted to use XMLHttpRequest object. I am getting "Access-Control-Allow-Origin" error.
I am setting following parameters in javascript.
var xhttp = new XMLHttpRequest();
xhttp.open("POST", request, true);
xhttp.onreadystatechange = function() {
if (this.status == 200) {
alert("Saved Successfully.");
}
};
xhttp.setRequestHeader("Content-type", "plain/text;charset=UTF-8");
xhttp.setRequestHeader("crossDomain", "true");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Accept", "text/plain; */*; *");
xhttp.send(data);
Following is jquery call, which works.
$.ajax({
type: "POST",
url: request,
data: data,
dataType: 'text',
crossDomain: "true",
statusCode: {
200: function(data) {
alert("Saved Successfully.");
}
}
});
I am setting following parameters to response object.
response.addHeader( "Content-Type", "text/plain" );
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods","GET,POST,OPTIONS");
response.addHeader("Access-Control-Allow-Headers","Content-Type, Content-
Range, Content-Disposition, Content-Description");
The same setup works for JQuery call, so I do not think problem with setup.
Can somebody please suggest what is missing?
FOLLOWING CODE WORKED:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", request, true);
xhttp.onreadystatechange = function() {
if (this.status == 200) { }};
//xhttp.setRequestHeader("crossDomain", "true");
xhttp.setRequestHeader("Accept", "text/plain; *//*; *");
//xhttp.withCredentials = true;
xhttp.send(data);