'enabling cors in codeigniter ( restserver by @chriskacerguis )

http.get request in agularJs controller works fine when my client app and api are in localhost. when api is moved to server., issue arised.

client side using angularJs

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

log gives: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/api/spots/2/0. This can be fixed by moving the resource to the same domain or enabling CORS.

i have added these two lines to my controller construct

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

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

still same error.



Solution 1:[1]

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'] = [];

Solution 2:[2]

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

Solution 3:[3]

Client side => AngularJs (running with Grunt in localhost:9000) Server side => php (codeIgniter solution) (running in localhost:80)

The only thing that worked for me was to add this lines into the webservices controller in my php project:

         /*
           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);

Solution 4:[4]

if you can use jQuery Ajax, then use this line in your script.

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

it solved the problem for me when i tried to post some string using jQuery Ajax from sidebar desktop gadget to the xampp php file.

Solution 5:[5]

To add to the answer by @amal-ajith headers should be added in the rest.php file. For example I needed to add my authorization token for Ionic 4 app api calls/requests and all I needed to do was add the header field the rest.php file and my cors error was taken care of.

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'
];

Solution 6:[6]

There a lot of possible solutions here but none of them worked for me. I did some digging and found something. I'm not gonna explain but I hope it works for you.

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

Solution 7:[7]

For me I used curl in one of the route controller. I am using codeignitor 4.

So make a controller naming anything you want.

make a method

use curl in a method:

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

use routes like this: /controller/method in our case index

reference: https://codeigniter4.github.io/userguide/incoming/controllers.html

Solution 8:[8]

Add the following code in the parent constructor of your controller

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

Solution 9:[9]

Add this to your config.php In order to send the access-control-allow-origin HTTP header to accept connection from everywhere.

$method = $_SERVER["REQUEST_METHOD"];

if ($method == 'OPTIONS') {
    header("access-control-allow-origin: *");
    die("");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haritsinh Gohil
Solution 2 muTheTechie
Solution 3 pingul
Solution 4 Sizzling Code
Solution 5
Solution 6 JPilson
Solution 7 Khorram Bin Salim Khondkar
Solution 8 Isaac Quarshie
Solution 9 Skatox