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

旧街凉风 提交于 2019-11-26 08:24:59

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/15602099/http-options-error-in-phil-sturgeons-codeigniter-restserver-and-backbone-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!