如何解决这个从角落到laravel的帖子?

时间:2015-12-02 08:58:08

标签: angularjs laravel

我在Angular Js + Ionic Framework中有一个表单,当将表单发布到在Laravel上运行的Web服务时,我遇到了以下问题:

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.

但是,如果我从Laravel网络服务(JSON)中提取数据,我根本不会遇到任何问题。

这是我在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

    });
};

})

更新:

在进一步探索后,我会关注此帖子 - http://let-aurn.github.io/laravel-5-cors/

不确定受保护的$除外= [         &#39; api.example.dev&#39;     ];

我假设api.example.dev我可以改为localhost:8888?

1 个答案:

答案 0 :(得分:2)

您需要在Laravel中启用CORS(跨源资源共享)。当你从Laravel中提取数据时,它很可能在标题中接受GET。你需要添加

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

请遵循此Tutorial