【发布时间】:2013-01-03 02:32:57
【问题描述】:
我正在开发一个 angularjs 应用程序,它使用 laravel 作为其后端服务器。 我无法从 laravel 访问数据,因为在每个 GET 请求之前,angular 首先发送一个 OPTION 请求,如下所示。
OPTIONS /61028/index.php/api/categories HTTP/1.1
Host: localhost
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: GET
Origin: http://localhost:3501
Access-Control-Request-Headers: origin, x-requested-with, accept
Accept: */*
Referer: http://localhost:3501/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: UTF-8,*;q=0.5
我已尝试通过在前置过滤器中添加以下代码来响应此问题
if (Request::getMethod() == "OPTIONS") {
$headers = array(
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'X-Requested-With, content-type'
);
return Response::make('', 200, $headers);
}
这会创建一个带有标题的响应:
Content-Encoding: gzip
X-Powered-By: PHP/5.3.5-1ubuntu7.11
Connection: Keep-Alive
Content-Length: 20
Keep-Alive: timeout=15, max=97
Server: Apache/2.2.17 (Ubuntu)
Vary: Accept-Encoding
access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE
Content-Type: text/html; charset=UTF-8
access-control-allow-origin: *
cache-control: no-cache
access-control-allow-headers: X-Requested-With, content-type
虽然设置了header,但是浏览器还是会报错
XMLHttpRequest cannot load http://localhost/61028/index.php/api/categories. Origin http://localhost:3501 is not allowed by Access-Control-Allow-Origin.
我还尝试将允许来源设置为请求标头中显示的来源,如下所示
$origin=Request::header('origin');
//then within the headers
'Access-Control-Allow-Origin' =>' '.$origin[0],
仍然是同样的错误 我究竟做错了什么?非常感谢任何帮助。
编辑 1
我目前正在使用一个非常丑陋的 hack,当收到 OPTIONS 请求时,我会覆盖 laravel 初始化。这是我在 index.php 中完成的
<?php
if ($_SERVER['REQUEST_METHOD']=='OPTIONS') {
header('Access-Control-Allow-Origin : *');
header('Access-Control-Allow-Methods : POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers : X-Requested-With, content-type');
}else{
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @version 3.2.13
* @author Taylor Otwell <taylorotwell@gmail.com>
* @link http://laravel.com
*/
我还必须将 allow-origin 标头添加到 before 过滤器中。
我知道这并不聪明,但这是我目前唯一的解决方案
【问题讨论】:
-
我很确定当我尝试这个时,我发现有些浏览器要求大小写正确。看起来 Laravel 正在将所有内容都小写,这在技术上是可以的,但可能仍然会失败。
-
@Evert 我注意到了这一点,并考虑使用内置的 php
header()函数。但是问题仍然存在。 -
那很奇怪。您是否还确保为 GET、PUT、DELETE 和 POST 请求发回所有这些标头?这是必需的..