在codeigniter中启用cors(restserver by @chriskacerguis)

one*_*nas 6 php codeigniter angularjs codeigniter-restserver

当我的客户端应用程序和api在localhost中时,agularJs控制器中的http.get请求正常工作.当api移动到服务器时,出现了问题.

客户端使用angularJs

$http.get('http://domain.com/api/spots/2/0').success(function(datas){
console.log(datas);
});
Run Code Online (Sandbox Code Playgroud)

log give:跨源请求被阻止:同源策略不允许在http://domain.com/api/spots/2/0上读取远程资源.这可以通过将资源移动到同一域或启用CORS来解决.

我已将这两行添加到我的控制器构造中

header("Access-Control-Allow-Origin: *");

header("Access-Control-Allow-Methods: GET");
Run Code Online (Sandbox Code Playgroud)

还是一样的错误.

Ros*_*oss 15

尝试添加OPTIONS允许的方法.

header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
Run Code Online (Sandbox Code Playgroud)

一旦设置了标题,请在方法'OPTIONS'后立即返回.

if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
    die();
}
Run Code Online (Sandbox Code Playgroud)

另见这个答案.

Angular发送符合W3C CORS规范的预检请求,该请求将在实际尝试之前检查正确的允许方法.

就个人而言,我发现Mozilla Developer Network CORS页面更容易阅读,以帮助理解CORS的流程.


小智 10

如果其他人遇到问题,在Codeigniter REST控制器的rest.php文件中启用CORS对我有用.这也清楚地记录在这里的评论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'
];

//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'] = [];
Run Code Online (Sandbox Code Playgroud)


muT*_*hie 6

我在控制器类中添加了以下构造函数

public function __construct($config = 'rest')
{
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    parent::__construct();
}
Run Code Online (Sandbox Code Playgroud)