Every we tried to access my REST Web Service via AJAX JQuery we've got blocked by Cross-Origin :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://***** (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
We use Java REST Web Service on Glassfish 3.1.2, the client using Firefox Quantum 57.
Please see our code bellow :
$.ajax({
type: 'POST',
url: webservice + "/webresources/ivi/syncPassphrase",
crossOrigin: true,
data :JSON.stringify({
'passPhrase' : passphrase
}),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
crossDomain: true,
success: function(data){
syncData = data["output"];
}, error: function(){
}
});
We've read from several answer on SO and have tried like this bellow :
$.ajax({
type: 'POST',
url: webservice + "/webresources/ivi/syncPassphrase",
crossOrigin: true,
data :JSON.stringify({
'passPhrase' : passphrase
}),
xhrFields: {
withCredentials: true
},
dataType: 'json',
async: true,
contentType: 'application/json; charset=utf-8',
crossDomain: true,
timeout: 20000,
beforeSend: function(xhr){
xhr.setRequestHeader("Access-Control-Allow-Origin",'http://111.111.111.111:8080');
},
success: function(data){
syncData = data["output"];
console.log("xxx1 " + syncData);
}, error: function(xhr, status, error) {
console.log("xxx2 " + xhr.responseText + " | " + status + " | " + error + " | ");
}
});
But code above still produce same error.
On the server side, we set allow cross origin every request and respond like this code bellow :
@Override
public void filter(final ContainerRequestContext requestContext,
final ContainerResponseContext cres) throws IOException {
cres.getHeaders().add("Access-Control-Allow-Origin", "*");
cres.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
cres.getHeaders().add("Access-Control-Allow-Credentials", "true");
cres.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
cres.getHeaders().add("Access-Control-Max-Age", "1209600");
}
I run out of idea. Any idea?
Thanks