避免 CORS 在 codeigniter 中不起作用

问题描述 投票:0回答:2

我正在尝试在我的 codeigniter 应用程序中使用 AJAX 请求。 在我的 codeigniter 控制器功能的末尾,我添加了

public somefunction(){

 $this->output->set_header('Access-Control-Allow-Origin: *');
 $this->output->set_header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE');
 $this->output->set_content_type('application/json');
// plan contains array
 return $this->output->set_output(json_encode($plan));
}

Normal get request works via server to server, but AJax calls shows the error.
XMLHttpRequest cannot load localhost:8888. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

这是ajax调用

self.information = function() {
      $.ajax({
          type: 'GET',
          url: '',
          contentType: 'application/json; charset=utf-8'
      })
      .done(function(result) {
        console.log(result);
      })
      .fail(function(xhr, status, error) {
          alert(error);
      })
      .always(function(data){
      });
  }

该网址有效,因为我用邮递员检查了它并得到了返回的数据。所以没问题。

php ajax codeigniter xmlhttprequest cors
2个回答
3
投票

我今天遇到了同样的问题,对我有用的是定义index_options方法

public function index_options() {
    return $this->response(NULL, REST_Controller::HTTP_OK);
}

并将我的构造函数更新为此

public function __construct(){
    parent::__construct();
    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, PUT, DELETE");
}

不幸的是,我对访问控制不够熟悉,无法解释为什么这对我有用。希望这有帮助。


0
投票

我建议您对 REST API 使用 RestServer,它的设置中有 CORS 管理。 只需在 application/config 文件夹中的rest.php 文件中设置一些设置即可:

$config['check_cors'] = true; //Set to TRUE to enable Cross-Origin Resource Sharing (CORS).
$config['allowed_cors_headers'] = ['Header1','Header2'...] //If using CORS checks, set the allowable headers here
$config['allowed_cors_methods'] = ['GET','POST','OPTIONS',...] //If using CORS checks, you can set the methods you want to be allowed
$config['allow_any_cors_domain'] = true; //Set to TRUE to enable Cross-Origin Resource Sharing (CORS) from any source domain
$config['allowed_cors_origins'] = []; //specify what origins is allowed ($config['allow_any_cors_domain'] must be false)
© www.soinside.com 2019 - 2024. All rights reserved.