gpt4 book ai didi

codeigniter - Phil Sturgeon 的 Codeigniter Restserver 和 Backbone.js 中的 HTTP OPTIONS 错误

转载 作者:行者123 更新时间:2023-12-03 15:07:43 27 4
gpt4 key购买 nike

我的 backbone.js当我尝试将模型保存到位于另一个主机/URL 上的 restful Web 服务时,应用程序抛出 HTTP OPTIONS not found 错误。
根据我的研究,我从中收集到 post那 :

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.


我试图通过以下方式解决这个问题:
  • 将 Backbone 中的 emulateHTTP 设置为 true。

  • Backbone.emulateHTTP = true;


  • 我还允许在 header 中允许所有 CORS 和 CSRF 选项。
    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");

  • 应用程序在 Backbone.emulateHTTP 时崩溃引入了一行代码。
    有没有办法响应 CodeIgniter RESTServer 中的 OPTIONS 请求,还有其他替代方法可以允许从谈话的地方禁用此请求吗?

    我找到了 this on Github作为一种解决方案。我不确定我是否应该使用它,因为它似乎有点过时了。

    最佳答案

    我遇到了完全相同的问题。为了解决这个问题,我在核心中有一个 MY_REST_Controller.php,我所有的 REST API Controller 都将它用作基类。我只是添加了一个这样的构造函数来处理 OPTIONS 请求。

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

    这只是检查请求类型是否为 OPTIONS,如果是,则返回请求的代码 200。

    关于codeigniter - Phil Sturgeon 的 Codeigniter Restserver 和 Backbone.js 中的 HTTP OPTIONS 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15602099/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com