我真的很难让CORS使用Slim和AngularJS
AngularJS HTTP请求:
$http({
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accepts: 'application/json'
},
url: 'https://apisite/v1/users/'
})
.success(function(data){
users.users_list = data.results;
})
.error(function(){
});
在API服务器上,我使用slim并具有以下功能:
use Slim\Slim as Slim;
Slim::registerAutoloader();
$slim = new Slim();
$http_origin = $slim->request->headers->get('Origin');
$slim->response->headers->set('Access-Control-Allow-Origin', '*');
$slim->response->headers->set('Access-Control-Allow-Credentials', 'true');
$slim->response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
$slim->response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
//Routes in here
$slim->run();
虽然我不总是喜欢这样设置标题,而不是纯粹根据选项请求,但它可以删除Access-Control-Allow-Origin
上的预检错误。我的问题是,每当我尝试访问API时,我都会在OPTIONS
上收到预检错误。我无法弄清楚如何在预检选项检查中恢复Slim的成功。
我尝试添加条件步骤以捕获选项并设置标题:
if($slim->request->isOptions()){
header("HTTP/1.1 200 OK");
}
然而,这似乎没有任何效果。我还试图为所有OPTIONS
请求创建一个通用路由,但又没有运气。
$slim->options('/(:request/)', function () use ($slim){
header("HTTP/1.1 200 OK");
});
我知道修复此问题可能非常简单,可能是因为我完全不了解两台服务器之间的请求过程以及需要哪些标头。任何帮助都会非常感激。
尝试加载AngularJS页面时输出错误:
OPTIONS https://apisite/api/v1/users/
(anonymous function) @ angular.js:10514sendReq @ angular.js:10333serverRequest @ angular.js:10045processQueue @ angular.js:14567(anonymous function) @ angular.js:14583Scope.$eval @ angular.js:15846Scope.$digest @ angular.js:15657Scope.$apply @ angular.js:15951done @ angular.js:10364completeRequest @ angular.js:10536requestLoaded @ angular.js:10477
XMLHttpRequest cannot load https://apisite/api/v1/users/. Response for preflight has invalid HTTP status code 404
答案 0 :(得分:0)
一个简单的解决方案可能是创建middleware:
use Slim\Slim as Slim;
Slim::registerAutoloader();
$slim = new Slim();
class CorsMiddleware extends \Slim\Middleware
{
public function call()
{
//The Slim application
$app = $this->app;
//Response
$response = $app->response;
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization');
$this->next->call();
}
}
$slim->add(new \CorsMiddleware());
$slim->get('/test', function () use ($slim){
echo "Test!";
});
$slim->run();
此应用程序中的所有响应都包含Access-Control-Allow-*
标题。
答案 1 :(得分:0)
您可以尝试修改.HTACCESS文件以在所有API中添加CORS支持
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"