How to Fix Getting Cross-Origin Request Blocked

using ngResource getting
Cross-Origin
Request Blocked: The Same Origin Policy disallows reading the remote
resource at
http://xxx.xxx.x.xx:xxxx/AuthProvider/rest/service/authenticate. This
can be fixed by moving the resource to the same domain or enabling CORS.

You might also try this:

Cheers,

The problem occurs as your app is not running on the same domain as your service. You need to configure your Server to accept those calls by adding the ‘Access-Control-Allow-Origin’ Header.

other thing to do: add a proxy to your ionic.project file:

 "proxies": [
    {
      "path": "/<your local url>",
      "proxyUrl": "http://<remote_url>"
    }
  ],

Hey guys,

I actually wrote a full step by step tutorial on how to do this, and you can view it here: Posting data from Ionic app to PHP server. I also created a Github project for it, so you can clone it and check out code there.

Hope this will help anyone who stumbles onto this question in the future.

Just so I give you the “main” point, which is as other guys basically said (but a bit more detailed), is the Access-Control-Allow-Origin. This is my “API”, in PHP:

<?php
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}


//http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
	$request = json_decode($postdata);
	$username = $request->username;

	if ($username != "") {
		echo "Server returns: " . $username;
	}
	else {
		echo "Empty username parameter!";
	}
}
else {
	echo "Not called properly with username parameter!";
}
?>
1 Like

Dear Auon,
Your solution works for me when i take that URL eg: http://localhost:8100/web

but when I run in app it still shows

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://172.16.8.70/web/sanchayarestservice/index.php/LGIWebServices/sanchaya. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

please advise

Thanks

I saw this solution alot and tried it, for easier Debugging and testing locally but it never really worked :face_with_raised_eyebrow:

did you get the solution??