Search code examples
phpionic-frameworkcorspreflight

CORS Issue on Ionic CLI 6.13.0


I'm trying to make an http post request in ionic with php on backend,..

Here's my code in ionic :

        let body = {
            'data': ['data [0]', 'data [1]']
        };
        let options = {
            headers : { 'Content-Type' : 'application/json' }
        };
        const ifSuccess = (response) => {
            console.log(response);
            this.data = response;
        };
        const ifFail = (response) => {
            this.error = 'Oops! Une erreur au niveau du serveur...';
        };
        this.http.post('http://localhost/cantine-itu/test', body, options).subscribe(ifSuccess, ifFail);

Here's the backend (in php flight) :

Flight::before('json', function () {
    header('Access-Control-Allow-Origin: http://localhost:8100');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE');
    header('Access-Control-Allow-Headers: *');
});

Flight::route('POST /test', function(){
    $data = Flight::request()->data;
    Flight::json($data);
});

I'm getting an error saying that : Access to XMLHttpRequest at 'http://localhost/cantine-itu/test' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. (error-image)


Solution

  • Are you getting this error from web browser or a particular device?

    Since this is local development and not production I would set to the most permissive possible.

      'capacitor://localhost',
      'ionic://localhost',
      'http://localhost',
      'http://localhost:8080',
    

    https://ionicframework.com/docs/troubleshooting/cors