$http No 'Access-Control-Allow-Origin' problem on POST

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!";
}
?>
5 Likes