Use Symfony as Web Service

I am developing a mobile app in Ionic framework and using Symfony framework as webservices. When I send data to the symfony controller, I got the error: Cross-origin request blocked: Same origin policy disallows reading remote resource at http: //localhost/Symfony/web/app_dev.php/login . (Reason: CORS header "Access-Control-Allow-Origin" is missing). Here is my code

angular.module('starter.services', [])
    .factory('Stack',function($http,$q,ApiEndpoint){

       var baseurl =ApiEndpoint.url;

      // alert(baseurl);
      // var baseurl =ApiEndpoint.url;
        return{

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

               var defer = $q.defer();

              // console.log(item);
               $http.post(Url,info).

                  success(function (data, status, headers, config) {

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

                return defer.promise;
       },

      }

    })

      

My ionic controller:

angular.module('starter.controllers', [])

.controller('login', function($scope,$state,Stack) {


$scope.user = {};

console.log($scope.user.username);

     $scope.signIn = function(){

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



  var data = "pass=" +  username + "&mobiles=" + password;
       Stack.Login(data).then(function(response){

      //  $scope.data = response.totalLease;

        });  
  }


  $state.go('login');

})

      

My Symfony Controller:

 public function loginAction()
 {
     $response = new Response(json_encode(array('data' => 'a')));
     $response->headers->set('Access-Control-Allow-Origin', '*');
 //   $response->headers->set("Access-Control-Allow-Methods: OPTIONS, GET, POST");
     $response->headers->set('Content-Type', 'application/json');

     return $response;
}

      

My routing:

sample_email:
    pattern:  /login/{_locale}.{_format}
    defaults: { _controller: AcmeDemoBundle:Demo:login, _format: json, _locale: en}
    requirements:
        _method:  GET|POST 
        _format: JSON         

      

+3


source to share


1 answer


Try to put this at the beginning of your symfony / .htaccess website

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers X-Requested-With,content-type,X-Forwarded-Proto
Header set Access-Control-Allow-Methods GET,POST,PUT,OPTIONS

      

This will allow all origin for your xhr calls. This is fine in a developer environment, but you'd better indicate your origin during production.



Also browsers use the OPTIONS method to check the availability of a web service.

More information on the OPTION method: RESTful API Methods; HEAD AND OPTIONS

+2


source







All Articles