无法在Laravel API中启用CORS?

时间:2014-12-21 07:45:01

标签: laravel laravel-4 cors

我正在尝试构建一个简单的Angular应用程序。我在Laravel中创建了一个API,它只有两条简单的路由,可以发回机场和航班的json数据。我已经将Angular应用程序配置为通过如下服务获取数据:

services.js

angular.module('airlineServices', ['ngResource'])
    .factory('Airport', function($resource){
        return $resource("http://angulair.rohanchhabra.in/airports/:id", {}, {
            query: { method: "GET", isArray: false }
        });
    });

现在,当我将资源用作放置在angular目录本身中的简单json文件时,它可以工作。但是当我尝试从我的服务中获取Laravel API中的数据时,如上面的代码中所示,我在控制台中看到一个错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://angulair.rohanchhabra.in/airports. This can be fixed by moving the resource to the same domain or enabling CORS.

我已经安装了一个允许启用CORS的包https://github.com/barryvdh/laravel-cors。配置文件如下所示:

<?php

return array(

    /*
     |--------------------------------------------------------------------------
     | Laravel CORS Defaults
     |--------------------------------------------------------------------------
     |
     | The defaults are the default values applied to all the paths that match,
     | unless overridden in a specific URL configuration.
     | If you want them to apply to everything, you must define a path with *.
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*') 
     | to accept any value, the allowed methods however have to be explicitly listed.
     |
     */
    'defaults' => array(
        'supportsCredentials' => false,
        'allowedOrigins' => array('*'),
        'allowedHeaders' => array('*'),
        'allowedMethods' => array('*'),
        'exposedHeaders' => array(),
        'maxAge' => 0,
        'hosts' => array(),
    ),

    'paths' => array(
        'api/*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('*'),
            'allowedMethods' => array('*'),
            'maxAge' => 3600,
        ),
        '*' => array(
            'allowedOrigins' => array('*'),
            'allowedHeaders' => array('Content-Type'),
            'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE'),
            'maxAge' => 3600,
            'hosts' => array('api.*'),
        ),
    ),

);

我甚至尝试在应用程序中添加代码:filters.php中的after(),如下所示:

App::after(function($request, $response)
{
    $response->headers->set('Access-Control-Allow-Origin', '*');
    return $response;
});

即使这样也无济于事。所以我继续尝试编辑.htaccess文件,如下所示:

Header set Access-Control-Allow-Origin "*"

我仍然遇到同样的错误。

如果我上面提到的代码没有帮助,我已将这两个存储库公开,以便每个人都可以看看:

Laravel API

Angular Application

我做错了什么?如何启用CORS以便我可以从任何远程应用程序使用API​​?

1 个答案:

答案 0 :(得分:3)

您的ngResource网址需要更改。这应该有效:

return $resource("http://angulairapi.rohanchhabra.in/airports", {}, {
    query: { method: "GET", isArray: false }
});

您需要您的ngResource URL需要允许更改OPTIONS标头。见https://laracasts.com/discuss/channels/requests/laravel-5-cors-headers-with-filters

从页面引用这应该有效:

App::before(function($request)
{
    // Enable CORS 
    // In production, replace * with http://yourdomain.com 
    header("Access-Control-Allow-Origin: *");
    header('Access-Control-Allow-Credentials: true');

    ifreturn $resource(Request:"http:getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed angulairapi.rohanchhabra.in Access-Control-Allow-Headers
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'X-Requested-With, Content-Type, X-Auth-Token/airports", Origin{}, Authorization'
        ];{
        return Response:query:make('You are connected to the{ API',method: 200"GET", $headers);
  isArray: false }
});

我自己没有使用laravel-cors,但是,您可能想尝试在路径中添加OPTIONS:

'*' => array(
    'allowedOrigins' => array('*'),
    'allowedHeaders' => array('Content-Type'),
    'allowedMethods' => array('POST', 'PUT', 'GET', 'DELETE', 'OPTIONS'),
    'maxAge' => 3600,
    'hosts' => array('api.*'),
),