Hi,
i have try to get an http post request with ionic but i receive this error:
Access to XMLHttpRequest at 'https://DDD.org/API/1.0/APINews.php' from origin 'http://192.168.1.22:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status
I have try with POSTMAN and the server respond correctly
I use this header in my PHP API (altervista):
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header("Access-Control-Allow-Origin: http://192.168.1.22:8100");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
Thank you all.
I solved it in the following way:
as the first call, in case of POST, the browser does a preflight (http “OPTIONS” method) which only checks the server. To authorize, simply return the CORS headers and return the http 200 status:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With');
header("Content-Type: application/json;");
/*foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}*/
switch ($_SERVER['REQUEST_METHOD']) {
case 'OPTIONS': // preflight
http_response_code(200);
exit;
break;
case 'POST':
$_POST = array_merge($_POST, json_decode(file_get_contents('php://input'),true));
$token = isset($_POST['token']) ? $_POST['token'] : NULL;
break;
case 'GET':
$token = isset($_GET['token']) ? $_GET['token'] : NULL;
break;
}
if ($token === null || $token !== 'mytoken') {
http_response_code(401);
echo json_encode(['response' => 'unauthorized']);
exit;
}
http_response_code(200);
echo json_encode(['mydata' => 'something']);
exit;