XAF
XAF

Reputation: 1472

avoiding CORS not working in codeigniter

I am trying to work with AJAX request in my codeigniter app. At the end of my codeigniter controller function, I added

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.

Here is the ajax calls

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){
      });
  }

The url works, since I checked it with postman and I get data returned. So no problem with that.

Upvotes: 2

Views: 7748

Answers (2)

Ra Light
Ra Light

Reputation: 11

I recommend to you to use RestServer for REST API which has CORS managing in it's settings. Just set some settings in rest.php file in application/config folder:

$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)

Upvotes: 0

Awad Maharoof
Awad Maharoof

Reputation: 2370

I came across the same issue today, what worked for me was defining the index_options method

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

and updating my the constructor to this

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");
}

Unfortunately I'm not familiar enough with access control to explain why this worked for me. Hope this helps.

Upvotes: 3

Related Questions