【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource- angular js请求的资源 Angular js 上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2015-09-01 08:40:03
【问题描述】:

我正在使用 php codeigniter restful api 作为服务器端和客户端应用程序的离子框架开发应用程序, 我正在尝试将客户端应用程序与服务器 api 连接,但我遇到了以下问题

XMLHttpRequest cannot load http://localhost:90/mrk/index.php/MRKGeneral_api/user_login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

我在客户端使用了下面的代码,

$scope.signIn = function(form) {
        if(form.$valid) {
            var postData = { 'username' : $scope.authorization.username, 'password' : $scope.authorization.password };

            $http({
                url: "http://localhost:90/mrk/index.php/MRKGeneral_api/user_login", method: 'POST',
                data: postData,
                headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
            }).then(function(result) { 
                if(result.status == 200) {
                    if(result.data.success) {
                        GeneralService.userType = result.data.usertype;
                        GeneralService.userData = result.data;
                        $scope.errormsg = result.data.message;
                        $state.go('/app/dashboard');
                    } else {
                        $scope.errormsg = result.data.message;
                    }
                } else {

                }

            });

        }
    }

在我的服务器端,我也设置了如下标题,

header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS") {
            die();
        }

但在请求的资源上仍然出现 No 'Access-Control-Allow-Origin' 标头。 Origin 'http://localhost:8100' 因此不允许访问。

【问题讨论】:

标签: javascript php angularjs codeigniter ionic-framework


【解决方案1】:

您需要在您的应用配置中允许跨域调用

app.config(function($httpProvider) {
    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;
});

【讨论】:

  • 您可以在您提供的代码中尝试 exit() 而不是 die() 吗? die() 关闭连接,而 exit() 不会。
  • 用exit()检查;也没有解决,还是一样的问题
  • 您能否检查对 OPTIONS 请求的响应中是否存在 Access-Control-Allow-Origin 标头。您可以查看浏览器控制台的网络选项卡。
猜你喜欢
  • 2023-04-04
  • 2015-08-29
  • 2017-02-22
  • 2018-10-31
  • 2019-07-21
  • 2016-08-17
  • 2018-01-03
  • 2018-06-09
相关资源
最近更新 更多