我的 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;
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/