在 AngularJS 和 CodeIgniter3 中开机自检数据时出现 CORS 错误


CORS error when POST data in AngularJS & CodeIgniter3

我使用的是AngularJS 1.3和CodeIgniter 3.0。

我成功地从本地主机中的 php 获取数据。但是我有错误"跨源请求被阻止"。我不知道,但这是一个搜索,请帮助我。

爪哇语

var module = angular.module('app', ['onsen']);
module.config(function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
module.controller('MasterController', function($scope, $http) {    
$scope.doLogin = function() {
    var postData = {"email": "aaa@bbb.ccc", "password": "pass"};
    var url = 'http://example/test?callback=JSON_CALLBACK';
    //This section is Error
    $http.post(url, postData, {withCredentials: true})
    .success(function(data, status, headers, config) {
        //
    }).error(function(data, status, headers, config) {
        //
    });
    //This section is Success
    $http.get(url).success(function(data, status, headers, config) {
        //
    }).error(function(data, status, headers, config) {
        //
    });
};
});

我尝试了"$http({url ~})",但结果是一样的。

.PHP

public function index() {
    $input_data = json_decode(trim(file_get_contents('php://input')), true);
    $this->output
    ->set_header("Access-Control-Allow-Origin: *")
    ->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin")
    ->set_content_type('application/json')
    ->set_output(json_encode($input_data));
}

尝试使用 .htaccess 允许 CORS。把它放在你的服务器.htaccess文件中

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

即使访问不同的端口也被浏览器视为跨域操作,到目前为止如何启用 CORS 的最佳指南可以在这里找到 http://enable-cors.org/