dcpartners
dcpartners

Reputation: 5446

How to solve this posting from angular into laravel?

I had a form in Angular Js + Ionic Framework and when post the form into web service running on Laravel I got the following issue:

XMLHttpRequest cannot load http://localhost:8888/practicelaravel-dev/public/programactivity. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

However, if I'm pulling the data from the Laravel webservice (JSON) I don't have a problem at all.

Here's the method that I'm using on the JS:

.controller('ProgramActivityAddController', function($scope, $http, $state, $localStorage) {
$scope.useruuid = $localStorage.useruuid;

$http.get('http://localhost:8888/practicelaravel-dev/public/programs/' + $scope.useruuid).success(function(data) {
  $scope.programs = data;
});

$scope.sendData = function (item, event) {
    $http({ 
      method: 'POST',
      url: 'http://localhost:8888/practicelaravel-dev/public/programactivity', 
      data: $scope.programactivity,
      headers: {'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS',
                'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept, Authorization'}
    })
    .success(function (data, status, headers, config) {
      $scope.PostDataResponse = data;
    })
    .error(function (data, status, headers, config) {
      $scope.RespondDetails = "Data: " + data +
        "<hr />status: " + status +
        "<hr />headers: " + headers +
        "<hr />config: " + config

    });
};

})

UPDATE:

After exploring further, I follow this post - http://let-aurn.github.io/laravel-5-cors/

Not sure about protected $except = [ 'api.example.dev' ];

I assume api.example.dev I could change to localhost:8888 ?

Upvotes: 0

Views: 379

Answers (1)

Imtiaz
Imtiaz

Reputation: 91

You need to enable CORS (Cross origin resource sharing) in Laravel. When you pulling data from Laravel most likely it accepts GET in header. You need to add

->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

Please follow this Tutorial.

Upvotes: 2

Related Questions