Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP OPTIONS error in Phil Sturgeon's Codeigniter Restserver and Backbone.js

My backbone.js application throwing an HTTP OPTIONS not found error when I try to save a model to my restful web service that's located on another host/URL.

Based on my research, I gathered from this post that :

a request would constantly send an OPTIONS http request header, and not trigger the POST request at all.

Apparently CORS with requests that will "cause side-effects on user data" will make your browser "preflight" the request with the OPTIONS request header to check for approval, before actually sending your intended HTTP request method.

I tried to get around this by:

  • Settting emulateHTTP in Backbone to true.

Backbone.emulateHTTP = true;

  • I also allowed allowed all CORS and CSRF options in the header.

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

The application crashed when the Backbone.emulateHTTP line of code was introduced.

Is there a way to respond to OPTIONS request in CodeIgniter RESTServer and are there any other alternatives to allow either disable this request from talking place?


I found this on Github as one solution. I am not sure if I should use it as it seems a bit outdated.

like image 268
Joel Dean Avatar asked Mar 24 '13 18:03

Joel Dean


2 Answers

I encountered exactly the same problem. To solve it I have a MY_REST_Controller.php in core and all my REST API controllers use it as a base class. I simply added a constructor like this to handle OPTIONS requests.

function __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, OPTIONS, PUT, DELETE");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
        die();
    }
    parent::__construct();
}

This just checks if the request type is OPTIONS and if so just dies out which return a code 200 for the request.

like image 197
jamespcole Avatar answered Oct 14 '22 17:10

jamespcole


You can also modify the $allowed_http_methods property in your subclass to exclude the options method. Previous versions of REST_controller did nothing with OPTIONS and adding this line seems to mimic that behavior:

protected $allowed_http_methods = array('get', 'delete', 'post', 'put');
like image 28
andymcintosh Avatar answered Oct 14 '22 18:10

andymcintosh