12

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.

onerinas
  • 198
  • 1
  • 1
  • 11

10 Answers10

25

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.

Community
  • 1
  • 1
Ross
  • 3,022
  • 1
  • 17
  • 13
  • i have added OPTIONS . still no change... im using[link] (https://github.com/chriskacerguis/codeigniter-restserver) for codeigniter ..anything to do with this? and do i have to make any changes to angularJS? – onerinas Sep 07 '14 at 02:37
  • Well, I'd first double check your browser dev tools and take a look at the network traffic / console log. Ensure you are getting a call sent out to the api end point [or not], then that your angular code is not throwing errors. – Ross Sep 07 '14 at 12:09
  • Thanks, looks like it should be right from the frontend call side of things. One thing to try is to die/exit the PHP script after setting the headers before anything else happens. So set your headers then immediately just die if the request method === 'OPTIONS'. See [this answer](http://stackoverflow.com/questions/15602099/http-options-error-in-phil-sturgeons-codeigniter-restserver-and-backbone-js?rq=1) for more details (try adding the Allow Headers part from that answer too) – Ross Sep 07 '14 at 15:28
  • 1
    thanks alot...! code in the link you specified works pretty well! added these code in my construct and worked! 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, OPTIONS, PUT, DELETE"); $method = $_SERVER['REQUEST_METHOD']; if($method == "OPTIONS") { die(); } – onerinas Sep 07 '14 at 16:01
  • Great to hear you've solved it - I've updated this answer and linked through to the other question for completeness! – Ross Sep 07 '14 at 16:07
  • Where to add these header("Access-Control-Allow-Methods: GET, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");?????? – Debdutta Panda Jul 04 '21 at 09:00
20

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'] = [];
Haritsinh Gohil
  • 5,818
  • 48
  • 50
Amal Ajith
  • 982
  • 8
  • 7
6

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();
}
muTheTechie
  • 1,443
  • 17
  • 25
1

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);
pingul
  • 3,351
  • 3
  • 25
  • 43
Alonso
  • 11
  • 1
1

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

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("");
}
Skatox
  • 4,237
  • 12
  • 42
  • 47
0

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.

Sizzling Code
  • 5,932
  • 18
  • 81
  • 138
  • It will only work if you are using jQuery Library. After defining Library, put that line in script file you have or in under script tags inside your html file.. – Sizzling Code Sep 07 '14 at 05:58
  • after that i have to call the api through jquery? if so im least preferred to this method because read somewhere using jquery and angular methods may conflict ( if not, please correct me ) – onerinas Sep 07 '14 at 13:51
  • @onerinas Yes you are right, it may conflict, it may not, i also used to use jquery with angular and it worked fine for me, but i just tested on small application. I posted this answer, that if u are willing to add jQuery then you can use jQuery CORS. I didn't gave much time to angular, dont know much about it.. Sorry. – Sizzling Code Sep 07 '14 at 15:20
  • tried now. still same issue., also here is how implmented: included this in header: and then ur code: jQuery.support.cors = true; in my contoller 1st line any wrong usage? i guess i have to make changes in api part. any thoughts? – onerinas Sep 07 '14 at 15:54
  • enabling cors in **codeigniter** not in **jQuery** – Rohan Kumar Jun 15 '21 at 06:14
0

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'
];
MuturiAlex
  • 338
  • 1
  • 8
0

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);
        }
JPilson
  • 1,075
  • 11
  • 10
0

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