离子源中的跨源请求被阻止

时间:2015-08-14 08:32:49

标签: php android angularjs symfony ionic-framework

Hello Friends我正在使用离子框架开发Android应用程序。在服务端我使用Symfony框架进行Web服务。我使用Web服务成功获取数据。但是当我发布数据时,我收到错误Cross-Origin Request Blocked这是我的代码:

.controller('login', function($scope,$state,Stack,$ionicPopup,$ionicLoading,$cordovaLocalNotification, $ionicPlatform) {




$scope.user = {};


      var username = $scope.user.username;
      var password = $scope.user.password;

       Stack.Login(username,password).then(function(response){

        var login = response.data;


        });  
  }

  $state.go('login');

})

服务就像:

Login:function(username,password){
        //alert(info);
           var Url = baseurl+'login';

           var defer = $q.defer();
           alert(username);
          // console.log(item);
           $http.post(Url,username).
              success(function (data, status, headers, config) {

                  defer.resolve(data);
              }).
              error(function (data, status, headers, config) {
                  defer.reject();
              });

            return defer.promise;
   },

在Symfony中:

public function loginAction()
         {
$response = new Response(json_encode(array('data' =>'Faliure')));
            $response->headers->set('Access-Control-Allow-Origin', '*');
            $response->headers->set('Content-Type', 'application/json');
            return $response;
}

1 个答案:

答案 0 :(得分:0)

最后经过大量搜索后,我找到了Cross-Origin Request Blocked的解决方案。实际上问题出在服务器端。

解决方案是安装此:

php composer.phar require nelmio/cors-bundle:~1.0

然后加入AppKernal.php:

new Nelmio\CorsBundle\NelmioCorsBundle(),

更新Config.yml文件:

nelmio_cors:
   defaults:
       allow_credentials: true
       allow_origin: []
       allow_headers: []
       allow_methods: []
       expose_headers: []
       max_age: 0
       hosts: []
   paths:
    '^/':
        allow_origin: ['*']
        allow_headers: ['origin', 'content-type']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
        max_age: 3600