这可能是一个简单而明显的东西,但我看不出问题出在哪里。经过一些研究后,我发现为了在laravel 4中启用CORS,应该在filters.php中添加以下内容:
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
所以当我在angularjs中做到这一点时,我的想法是:
app.factory('RestFactory', function ($http) {
var BASE_URL = 'url_to_the_site';
return {
get: function (target) {
return $http({method: 'GET', url: BASE_URL + target});
},
post: function (target, data) {
return $http.post(BASE_URL + target, data);
}
};
});
它应该正常吗?在开发模式下在localhost:8000中运行Laravel 4时似乎可以正常工作。但是,当我将Laravel转移到我的网站并尝试访问网站网址时,我得到的是:
请求的资源上没有'Access-Control-Allow-Origin'标头。
那我在这里做错了什么?它适用于本地,BASE_URL也可以在使用浏览器访问网址时工作,所以我在这里缺少什么?