CORS problem in app with Access-Control-Allow-Origin


#1

Hello, everybody,

I have created a rest api on my server to do some tests following Matt’s tutorial on youtube:
Ionic Creator Tutorials // Using APIs with Angular $http // Part 1 (https://www.youtube.com/watch?v=DJotOLNrM8M)

I just want to try sending a couple of data from a form and receive a response.
When I send the data to my server I get this error in the network console:
Failed to load https://mydomain.com/usersonapis: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://creator.ionic.io’ is therefore not allowed access.

I tried to give access to https://creator.ionic.io using .htaccess but it doesn’t work.

Using an chrome extension to send data via json (postman) works perfectly.

Using this app, the data is send like this:
POST /clients/web/usersonapis HTTP/1.1
Host: mydomain. com
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 03764585-20c4-70bc-f92a-c580ba7fcbce
{
“username”:“dumb.”
“pass”:“t3stp4ss”
}

Can someone give me a hint as to what configuration I should apply on my server to avoid this error?
Thanks.


#2
<?php
/**
 * User: benjohansen
 * email: benj@webspinr.com
 */

$token = null;
$headers = apache_request_headers();
if (!$headers) {
    $headers = http_get_request_headers();
}

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );


$username = 'dumb';
$password = 't3stp4ssY=';

if (!$_SERVER['PHP_AUTH_USER']) {
    $passfail = 'Fail';
} else {
    if ($_SERVER['PHP_AUTH_PW'] == $password && $_SERVER['PHP_AUTH_USER'] == $username) {
        $passfail = 'Pass';
    } else {
        $passfail = 'Fail';
    }
}

$ret = [
    'result' => 'OK',
    'Auth' => $passfail
];
print json_encode($ret);


#3

Thank you. As soon as I can, I’ll try your solution.:wink: