Hi,
For my application, I try to speak with a backend.
I try to pass my app form ionic 1.X to Ionic 2, but I have this error :
XMLHttpRequest cannot load http://volodiaja.net/BookSquare/api.php?callback=JSON_CALLBACK&function=library&user=1.
No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Origin ‘http://localhost:8100’ is therefore not allowed access.
My code is :
In backend : api.php
<?php
header('Content-Type: application/json; charset=utf-8');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = " booksquare";
$param1 = $_GET['param1'];
//pour retrocompatibilité
$user = $_GET['user'];
$auteur = $_GET['auteur'];
if($_GET['function']=='library')
{
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("select Titre, Auteur, ISBN, ImageURL, GbookImageURL, DatePublished from Books where User_ID = :User_ID");
$stmt->bindParam(':User_ID', $user);
$data = array();
$stmt->execute();
$records = $stmt->fetchAll();
foreach ($records as &$record) {
$data[] = array("img" => $record[GbookImageURL], "titre" =>$record[Titre],"date" =>$record[DatePublished] ,"isbn" =>$record[ISBN]);
}
echo $_GET['callback'] . '('.json_encode($data).')';
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
}
?>
And in my ionic 2 app, I have
this.http.get('http://volodiaja.net/BookSquare/api.php?callback=JSON_CALLBACK&function=library&user=1').map(res => res.json()).subscribe(data => {
// value = data.data.children;
console.log(data);
},
err => {
console.log("Oops!");
});
}
But before with ionic 1, I have NO error and I have this :
$http({method: 'JSONP', url: "http://volodiaja.net/BookSquare/api.php?callback=JSON_CALLBACK&function=library&user=1"})
.success(function(data, status) {
var i = 0;
data.forEach(function(value) {
$scope.yesEchanges.push({id: i, titre: value.titre, auteur:value.date , image: img/img.png'});
i++;
});
})
.error(function(data, status) {
console.log(data || "Request failed");
});