enabling cors in codeigniter ( restserver by @chriskacerguis ) enabling cors in codeigniter ( restserver by @chriskacerguis ) codeigniter codeigniter

enabling cors in codeigniter ( restserver by @chriskacerguis )


Try adding OPTIONS to the allowed methods.

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

and return immediately when the request is method 'OPTIONS' once you have set the headers.

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

See also this answer.

Angular sends a W3C CORS spec compliant preflight request that will check for the right allowed methods before actually attempting it.

Personally, I find the Mozilla Developer Network CORS page a bit easier to read on the matter to help understand the flow of CORS.


If anyone else is facing the issue, enabling CORS in rest.php file of Codeigniter REST Controller worked for me. This is also clearly documented in comments here 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'] = [];


I've added the following constructor in my controller class

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