I have a strange problem that I have been working on for a couple of days.
The problem is related to Cross-Origin Resource Sharing(CORS), I am making an Angular GET
request and able to see in the developer tools of Firefox/Chrome that JSON response body is received, however JavaScript (or the browser, or the server) is refusing to hand me the response body.
Here is my request:
$http = angular.injector(["ng"]).get("$http"); //angular http object
$http = angular.injector(["ng"]).get("$http");
$http({
method: 'GET',
url: 'api.example.com/myPath',
headers: {
'Content-Type': 'application/json',
}
}).then(function successCallback(response) {
alert("succeed: db "+JSON.stringify(response)); //this is not called
}, function errorCallback(response) {
alert("failed: " + JSON.stringify(response));//this is called
});
As mentioned in the comments the fail function is called not the success. I can mention/post the Stack-overflow and other links that I have been to here, but there are like 50 of them, so here are some of them:
Headers I have tried (beside what shown in the code):
"headers": {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': '*'
}
"headers": {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*'
}
"headers": {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': '*'
}
"headers": {
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': '*'
}
"headers": {
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*'
}
Tried all the above, some of them will not receive JSON response, instead the Send OPTIONS
request and stop.
This is what Firefox output looks like:
And here is the Alert function output :
failed: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api.example.com/myPath","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"","xhrStatus":"error"}
Other things I tried: Installing Plugin for Chrome called CORS : Was not effective at all, no difference
Note The Endpoints server is not NodeJS, It is Java, Most of the answers I have come across online suggest adding these headers at the server, but my colleagues insist that this problem can be solved using front-end Angular (Especially after they saw that the correct response body Json information is actually coming from the server as shown in the pictures attached)