简体   繁体   中英

Angular4 app with PHP Api CORS request issue

I am trying to POST in Angular4 Ionic application, i have read all of the stack overflow posts and done what they say. In my PHP i have added

header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Expose-Headers: Content-Length, X-JSON");
header ("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header ("Access-Control-Allow-Headers: *");

I am able to do the post from POSTMAN successfully but from debugging app in android i get ...from origin 'http://localhost: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'm just trying a simple post in angular4 ionic app..

getImages() {
       this.http.post(url, {
      title: 'foo',
      body: 'bar',
      userId: 1
    })
      .subscribe(
        res => {
          console.log(res);
        },
        err => {
          console.log("Error occured");
        }
      );
    }

I fixed this issue using the below php code to specifically allow from my localhost, which i will remove when i go live.

$http_origin = $_SERVER['HTTP_ORIGIN'];

$allowed_domains = array(
    'http://localhost:8100',
    'localhost',
    '*',
    'localhost:8100',
    'http://www.detdev.co.uk',
    'detdev.co.uk'
);

if (in_array(strtolower($http_origin), $allowed_domains))
{  
    // header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Origin: $http_origin");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        header("Access-Control-Allow-Headers: Authorization, Content-Type,Accept, Origin");
    exit(0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM