【问题标题】:enabling cors in codeigniter ( restserver by @chriskacerguis )在codeigniter中启用cors(@chriskacerguis的restserver)
【发布时间】:2014-10-31 10:01:02
【问题描述】:

当我的客户端应用程序和 api 在本地主机中时,agularJs 控制器中的 http.get 请求工作正常。 当 api 被移动到服务器时,出现了问题。

使用 angularJs 的客户端

$http.get('http://domain.com/api/spots/2/0').success(function(datas){
console.log(datas);
});

日志给出: 跨域请求被阻止:同源策略不允许读取位于http://domain.com/api/spots/2/0 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。

我已将这两行添加到我的控制器构造中

header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Methods: GET");

还是一样的错误。

【问题讨论】:

    标签: php angularjs codeigniter codeigniter-restserver


    【解决方案1】:

    在控制器的父构造函数中添加以下代码

    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, OPTIONS, POST, GET, PUT");
    header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
    

    【讨论】:

      【解决方案2】:

      对我来说,我在其中一个路由控制器中使用了 curl。我正在使用 codeignitor 4。

      所以制作一个控制器来命名你想要的任何东西。

      制作方法

      在方法中使用 curl:

      public function index() { //code using curl or file get contents depending upon your api}

      使用这样的路由:/controller/method 在我们的案例索引中

      参考:https://codeigniter4.github.io/userguide/incoming/controllers.html

      【讨论】:

        【解决方案3】:

        这里有很多可能的解决方案,但没有一个对我有用。 我做了一些挖掘,发现了一些东西。我不会解释,但我希望它对你有用。

        Add the following block of code in your controller file .

               if (isset($_SERVER['HTTP_ORIGIN'])) {
                    // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
                    // you want to allow, and if so:
                    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
                    header('Access-Control-Allow-Credentials: true');
                    header('Access-Control-Max-Age: 86400');    // cache for 1 day
                }
                    // Access-Control headers are received during OPTIONS requests
                if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        
                    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                        // may also be using PUT, PATCH, HEAD etc
                        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
        
                    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
        
                    exit(0);
                }
        

        【讨论】:

          【解决方案4】:

          如果其他人面临这个问题,在 Codeigniter REST 控制器的 rest.php 文件中启用 CORS 对我有用。这也清楚地记录在 cmets 中 https://github.com/chriskacerguis/codeigniter-restserver/blob/master/application/config/rest.php

          //Change this to TRUE
          $config['check_cors'] = TRUE;
          
          //No change here
          $config['allowed_cors_headers'] = [
            'Origin',
            'X-Requested-With',
            'Content-Type',
            'Accept',
            'Access-Control-Request-Method',
            'Authorization',
          ];
          
          //No change here
          $config['allowed_cors_methods'] = [
            'GET',
            'POST',
            'OPTIONS',
            'PUT',
            'PATCH',
            'DELETE'
          ];
          
          //Set to TRUE to enable Cross-Origin Resource Sharing (CORS) from any source domain
          $config['allow_any_cors_domain'] = TRUE;
          
          
          //Used if $config['check_cors'] is set to TRUE and $config['allow_any_cors_domain'] is set to FALSE. 
          //Set all the allowable domains within the array
          //e.g. $config['allowed_origins'] =['http://www.example.com','https://spa.example.com']
          
          $config['allowed_cors_origins'] = [];
          

          【讨论】:

          • 是的,就是这样。
          • 谢谢,完美运行!这是正确的解决方案!使用这个。
          • 是的,这是最简单的答案,我在 codeigniter 中的 cors 问题已解决
          • 这适用于 codeigniter 版本 3.1.11。如果您有疑问,此文件是您项目中config/rest.php 路径中添加的文件,无需将其导入任何自定义控制器。
          【解决方案5】:

          要通过@amal-ajith 标题添加到答案中,应将其添加到rest.php 文件中。例如,我需要为 Ionic 4 应用程序 api 调用/请求添加我的授权令牌,我需要做的就是在 rest.php 文件中添加标题字段,并且我的 cors 错误得到了处理。

          Access to XMLHttpRequest at 'http://localhost/ci/index.php/api/validate_token' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.
          
          
          //No change here
          $config['allowed_cors_headers'] = [
            'Origin',
            'X-Requested-With',
            'Content-Type',
            'Accept',
            'Access-Control-Request-Method',
            'Authorization'
          ];
          

          【讨论】:

            【解决方案6】:

            我在控制器类中添加了以下构造函数

            public function __construct($config = 'rest')
            {
                header('Access-Control-Allow-Origin: *');
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
                parent::__construct();
            }
            

            【讨论】:

              【解决方案7】:

              客户端 => AngularJs(在 localhost:9000 中使用 Grunt 运行) 服务器端 => php(codeIgniter 解决方案)(在 localhost:80 中运行)

              唯一对我有用的就是将此行添加到我的 php 项目中的 webservices 控制器中:

                       /*
                         here you do whatever you do to build the $data 
              
                       */
              
                      //but just before returning the method data add this
              
                      header('Content-type: application/json');
                      header("Access-Control-Allow-Origin: *");
                      header("Access-Control-Allow-Methods: GET");
                      header("Access-Control-Allow-Methods: GET, OPTIONS");
                      header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
                      echo json_encode($data, JSON_NUMERIC_CHECK);
              

              【讨论】:

                【解决方案8】:

                尝试将OPTIONS 添加到允许的方法中。

                header("Access-Control-Allow-Methods: GET, OPTIONS");
                header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
                

                一旦你设置了标题,当请求是方法'OPTIONS'时立即返回。

                if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
                    die();
                }
                

                另见this answer

                Angular 发送一个W3C CORS spec compliant preflight request,它将在实际尝试之前检查正确的允许方法。

                就我个人而言,我发现Mozilla Developer Network CORS page 在这件事上更容易阅读,以帮助理解 CORS 的流程。

                【讨论】:

                • 我添加了 OPTIONS 。仍然没有变化......我正在使用[link](github.com/chriskacerguis/codeigniter-restserver)作为codeigniter ..与此有关吗?我是否必须对 angularJS 进行任何更改?
                • 好吧,我首先要仔细检查您的浏览器开发工具并查看网络流量/控制台日志。确保您收到发送到 api 端点的调用 [或没有],然后您的 Angular 代码不会引发错误。
                • 谢谢,看起来它应该是从前端调用端开始的。要尝试的一件事是在设置标头后终止/退出 PHP 脚本,然后再发生其他任何事情。因此,如果请求方法 === 'OPTIONS',请设置您的标头然后立即死亡。有关更多详细信息,请参阅this answer(也尝试从该答案中添加 Allow Headers 部分)
                • 非常感谢...!您指定的链接中的代码效果很好!在我的构造中添加了这些代码并工作了! 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("访问控制允许方法:GET、POST、OPTIONS、PUT、DELETE"); $method = $_SERVER['REQUEST_METHOD']; if($method == "OPTIONS") { die(); }
                • 很高兴听到您解决了它 - 我已经更新了这个答案并链接到另一个问题以确保完整性!
                【解决方案9】:

                如果您可以使用 jQuery Ajax,请在您的脚本中使用这一行。

                jQuery.support.cors = true; // force cross-site scripting (as of jQuery 1.5)
                

                当我尝试使用 jQuery Ajax 从侧边栏桌面小工具将一些字符串发布到 xampp php 文件时,它为我解决了这个问题。

                【讨论】:

                • 只有当你使用 jQuery 库时它才会起作用。定义库后,将该行放在您拥有的脚本文件中或在您的 html 文件中的脚本标签下..
                • 之后我必须通过jquery调用api吗?如果是这样,我最不喜欢这种方法,因为使用 jquery 和角度方法在某处读取可能会发生冲突(如果不是,请纠正我)
                • @onerinas 是的,你是对的,它可能会发生冲突,也可能不会,我也曾经使用带有 Angular 的 jquery,它对我来说效果很好,但我只是在小型应用程序上进行了测试。我发布了这个答案,如果你愿意添加 jQuery,那么你可以使用 jQuery CORS。我没有给 Angular 太多时间,对此了解不多。抱歉。
                • 现在试过了。仍然是同样的问题。,这也是如何实现的:将其包含在标题中: 然后你的代码:jQuery.support.cors = true;在我的控制器第一行有任何错误的用法吗?我想我必须在 api 部分进行更改。有什么想法吗?
                • codeigniter 中而不是在 jQuery 中启用 cors
                猜你喜欢
                • 2013-10-21
                • 2016-08-18
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2015-08-17
                • 2011-10-28
                相关资源
                最近更新 更多