【发布时间】:2015-02-19 15:52:38
【问题描述】:
我正在尝试构建一个简单的 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.
我已经安装了一个包https://github.com/barryvdh/laravel-cors,它应该启用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.*'),
),
),
);
我什至尝试在 filter.php 中的 App:after() 中添加代码,如下所示:
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
});
即使这样也无济于事。所以我继续尝试编辑 .htaccess 文件,如下所示:
Header set Access-Control-Allow-Origin "*"
我仍然遇到同样的错误。
如果我上面提到的代码没有帮助,我将两个存储库都公开了,以便大家看看:
我做错了什么?如何启用 CORS 以便我可以从任何远程应用程序使用 API?
【问题讨论】: