http.get request in agularJs controller works fine when my client app and api are in localhost. when api is moved to server., issue arised.
client side using angularJs
$http.get('http://domain.com/api/spots/2/0').success(function(datas){
console.log(datas);
});
log gives: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://domain.com/api/spots/2/0. This can be fixed by moving the resource to the same domain or enabling CORS.
i have added these two lines to my controller construct
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
still same error.
Try adding OPTIONS
to the allowed methods.
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
and return immediately when the request is method 'OPTIONS' once you have set the headers.
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
See also this answer.
Angular sends a W3C CORS spec compliant preflight request that will check for the right allowed methods before actually attempting it.
Personally, I find the Mozilla Developer Network CORS page a bit easier to read on the matter to help understand the flow of CORS.