2015-11-15 69 views
0

我试图做使用离子HTTP服务的GET请求。但我已经来到这个跨起源错误,我得到:如何离子USE CORS角

XMLHttpRequest cannot load http://127.0.0.1/webService/getBlogs.php. Origin http://localhost is not allowed by Access-Control-Allow-Origin 

以及我搜索解决方案,但由于我有限的了解,我是迷路了,不知道该怎么办。 有人说去ionic.project和改变代理一个完整的URL。 有人说改变节点JS服务器的一些代码,我不知道是哪个文件,并在那里我可以找到。

有人能指导我如何设置CORS并在设定的头信息?

这里是我下面的代码:

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); 
      }); 
    } 
} 

和PHP Web服务

<?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(); 

?> 
+0

这可能对你有帮助 http://blog.ionic.io/handling-cors-issues-in-ionic/ –

回答

0

我猜你已经错过了在后端这条线。我不是一个PHP程序员,但这是我在我的节点应用程序中完成的。

"Access-Control-Allow-Origin", 'http://localhost:8100'

,并在我的前端

myApp.config(function($stateProvider, $urlRouterProvider, $httpProvider) { 

    // CORS 

    $httpProvider.defaults.withCredentials = true; 
    $httpProvider.defaults.useXDomain = true; 
    delete $httpProvider.defaults.headers.common['X-Requested-With']; 

    // Ionic uses AngularUI Router which uses the concept of states 
    // Learn more here: https://github.com/angular-ui/ui-router 
    // Set up the various states which the app can be in. 
    // Each state's controller can be found in controllers.js 
    $stateProvider 

    .state('initial', { 
     url: "/initial", 
     templateUrl: 'templates/initial.html', 
     controller: 'initialController' 

    }); 
}); 
+0

你是什么意味着在节点应用程序? –

+0

对于后端我使用的NodeJS。你使用php –