i am trying to do a get request using ionic http service. But i have come to this cross origin error which i got:
XMLHttpRequest cannot load http://127.0.0.1/webService/getBlogs.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin
well i searched for solutions but due to my limited understanding i was lost and don't know what to do. Some say go to ionic.project and change the proxy to a full url. Some say change some code in node js server and i don't know which file and where i can find that.
Can someone guide me on how to setup CORS and where to set a header information?
Here is my code below:
var TMSApp = angular.module("TMSApp",["ionic"]);
TMSApp.service("TMSSvc",["$http","$rootScope",TMSSvc]);
TMSApp.controller("TMSCtrl",["$scope","$sce","$ionicLoading","TMSSvc",TMSCtrl]);
function TMSCtrl($scope, $sce,$ionicLoading,TMSSvc){
$ionicLoading.show({
template: 'Loading Blogs...'
});
$scope.blogs = [];
$scope.$on("TMSApp.blogs",function(_, result){
result.posts.forEach(function(b){
$scope.blogs.push({
name:b.author.name,
title:$sce.trustAsHtml(b.title),
avatar:b.author.avatar_URL
});
});
$ionicLoading.hide();
});
TMSSvc.loadBlogs();
}
function TMSSvc($http,$rootScope){
this.loadBlogs= function(){
$http.get("http://localhost/IonicDemo/webService/getBlogs.php")
.success(function(result){
$rootScope.$broadcast("TMSApp.blogs",result);
});
}
}
and PHP web service
<?php
require_once("conn.php");
class getBlogs{
function __construct($db){
$this->mysqli = $db->getLink();
}
function getAllBlogs(){
header("HTTP/1.1 400 VALID REQUEST");
header("Access-Control-Allow-Origin: *");
header("content-type:application/json");
$qry = "SELECT * FROM services";
$res = $this->mysqli->query($qry);
if(!$res){
echo $this->mysqli->error;
}
$data = array();
while($row = $res->fetch_assoc()){
$data = $row;
echo json_encode($data);
}
//$data;
//echo $data;
}
}
$gb = new getBlogs($db);
$gb->getAllBlogs();
?>