Search code examples
phphttpionic-frameworkxmlhttprequest

Origin http://localhost:xxxx is not allowed by Access-Control-Allow-Origin


I'm trying to fetch some data from my mySQL DB stored on 000webhost, and Ionic show me that error message:

enter image description here

I've read that I need to enable CORS policy, but don't understand on where I should. That's the fetch_data.php code:

<?php
require 'config.php';

$query = "SELECT lat, lng FROM gps WHERE id = (SELECT MAX(ID) FROM gps)";

$result = mysqli_query($con, $query);

if($result === FALSE) { 
    printf("Error: %s\n", mysqli_error($con));
}  

$response = array();

while($row = mysqli_fetch_array($result)){
    array_push($response, array(“lat”=>$row[0],“lng”=>$row[1]));
}

echo json_encode(array($response));
?>

Solution

  • add to index.php

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS, PATCH, DELETE');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Headers: Authorization, Content-Type, x-xsrf-token, x_csrftoken, Cache-Control, X-Requested-With');