CORS与Laravel 4
我正在编写一个API,并使用Laravel 4来实现这一点。我的 API 位于不同的域。让我们假设它是:http://api-example.com/
当我尝试通过Backbone从我的Web应用程序(即)使用基本身份验证向我的api发出ajax请求时,它有时工作得很好,但有时却不能。我试图找出原因。以下是我的过滤器和过滤器。mydomain.com
App::before
App::after
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => 'http://mydomain.com',
'Allow' => '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', 'http://mydomain.com');
$response->headers->set('Allow', '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;
});
问题是,当我尝试使用凭据向其发出发布请求时,API会检查数据库并获取用户的API密钥。这工作正常。但是当我尝试向chrome发出POST请求时,只会给我以下错误:/login
/users
XMLHttpRequest cannot load http://api-example.com/users. Origin http://mydomain.com is not allowed by Access-Control-Allow-Origin.
我尝试了一切,比如设置我可以从互联网上找到的一切。但到目前为止,没有任何效果。我不知道我该怎么办。Access-Control-Allow-Origin
'*'