3

我在 Firefox 上遇到了 AngularJS 1.08 和 CORS 的奇怪问题。我的 AngularJS 看起来像这样:

var MyApp = angular.module('MyApp');

MyApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

$http({
  dataType : 'json',
  url : 'http://api.example.com/restful',
  withCredentials : true,
  method: 'POST',
  data : {val1 : 'Test'}
}).success(function(response) { console.log(response)}).error(function(response) { console.log(response)});

PHP 端如下所示:

header('Access-Control-Allow-Origin: '. $_SERVER['HTTP_ORIGIN'] );
        header('Access-Control-Allow-Credentials: true' );
        header('Access-Control-Request-Method: *');
        header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-requested-with,Content-Type');
        header('X-Frame-Options: DENY');

if(strtolower($_SERVER['REQUEST_METHOD']) == 'get') {
   //DO XYZ
} else if (condition) {
   //DO DEF
}

这在 Chrome 和 Safari 以及 FireFox $_GET 请求上工​​作正常,但不是 $_POST。在 Firefox 和 Apache 上,我得到一个错误 500,在 Nginx 上它在没有数据的情况下执行,并抛出一个空的错误消息。我的 CORS 设置有问题吗?

4

1 回答 1

0

$_POST并且$_GET不起作用,您应该使用此代码来读取从角度发送的数据

                $data = file_get_contents("php://input");
                $objData = json_decode($data);

我强烈建议看看AngularPHP,并省去一些麻烦

于 2014-01-09T12:25:50.927 回答