CORS与Laravel 4

2022-08-30 23:43:49

我正在编写一个API,并使用Laravel 4来实现这一点。我的 API 位于不同的域。让我们假设它是:http://api-example.com/

当我尝试通过Backbone从我的Web应用程序(即)使用基本身份验证向我的api发出ajax请求时,它有时工作得很好,但有时却不能。我试图找出原因。以下是我的过滤器和过滤器。mydomain.comApp::beforeApp::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'*'


答案 1

标头名称中存在错误。

header('Allow', 'GET, POST, OPTIONS'); // This is wrong.

header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // This is right.              

答案 2

制作一个花哨的响应对象并返回它,然后让页面进程运行是没有意义的,因为它会消除您的CORS标头并继续使用通常的内容。

App::before(function($request)
{
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {

        header('Access-Control-Allow-Origin', 'http://mydomain.com');
        header('Allow', 'GET, POST, OPTIONS');
        header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');
        header('Access-Control-Allow-Credentials', 'true');

        exit;
    }
});

推荐