AngularJS & Laravel CORS,POST 在预检选项后停止

AngularJS & Laravel CORS, POST stops after preflights OPTIONS

这是一只想为 post 工作但在飞行前测试中失败的鸟的故事...

使用 Laravel 构建的应用被用作 RESTful API 和 AngularJS/ionic。 我的 API 呼叫工作正常,直到...由于未知原因停止。 虽然我为调用的 angularJS 端设置了 withCredentials,但预检选项没有发送 cookie,但我从 Laravel 收到了一个。我们如何禁用 return cookie laravel_session 的选项? 它弄乱了 CORS,因为它设置了一个新的 session,这显然在每个 POST 上都是不同的。 对于 Laravel 端,我使用来自 @barryvdh 的包 Laravel/CORS 具有以下配置:

 '*' => array(
'supportsCredentials' => true,
'allowedOrigins' => array('*'),
'allowedHeaders' => array('*'),
'allowedMethods' => array('POST', 'PUT', 'GET', 'PATCH', 'OPTIONS', 'DELETE'),
'maxAge' => 36000,
'hosts' => array('api.*'),
)

在 Angular 方面,我有以下内容:

$http({
method: 'POST',
url: 'http://api.blabla.local/banana',
data: data,
withCredentials: true
})

我的 GET 调用工作正常,我在应用程序启动时有一个 运行 从 laravel 获取 CSRF,我在需要时发回。

现在发生以下情况:
1. Preflight OPTIONS > 请求没有 session 的 cookie。 Reponse = 200 带有不同的 session cookie,这将导致 CSRF 始终发生。 [想法:withCredentials 不适用于 OPTIONS 调用]
2. POST > 500 失败,在 headers 中我没有看到任何响应,但它确实发送了 cookie/session [想法:凭证已传递给它,但它们也是错误的,因为它们由于预检选项,服务器端发生了变化]。错误消息说它不是授权来源。

这是怎么回事?我已经尝试了几个小时并检查了很多其他 posts 但似乎没有任何帮助!我可以摆脱预检吗?或者是其他地方的问题(服务器端我使用 Laravel Homestead)? 我觉得真正的问题是 OPTIONS return 是一个 session cookie,或者只是请求确实包含一个!

感谢您的帮助,我已经被困了几个小时,我快要发疯了...

JWT 可能对 ionic 和 angular 有好处..

勾选http://packalyst.com/packages/package/tymon/jwt-auth 还有 https://www.youtube.com/watch?v=vIGZxeQUUFU

在 L4.2 下的 filters.php 中,我最终使用了这个: 这个问题很老,所以不确定这是我唯一做的事情,但看起来像:

App::before(function($request)
{
    //
    // Enable CORS 
    // In production, replace * with http://yourdomain.com 
    header("Access-Control-Allow-Origin: http://mydomain.local");
    header('Access-Control-Allow-Credentials: true'); //optional
    if (Request::getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        $headers = [
            'Access-Control-Allow-Methods'=> 'GET, POST, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type'
        ];
        return Response::make('You are connected to the API', 200, $headers);
    }

});


App::after(function($request, $response)
{
    //
});