我正在开发一个使用laravel作为其后端服务器的angularjs应用程序。 我有麻烦,因为每个GET请求之前访问来自laravel数据,角先发送OPTION请求如下laravel处理OPTION http方法请求
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
虽然标头设置的响应,浏览器仍然会引发错误
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
我现在使用的一个非常丑陋的黑客在这里我过程接收到OPTIONS请求时laravels初始化。这我已经在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 <[email protected]>
* @link http://laravel.com
*/
我还必须将allow-origin头添加到之前的过滤器。
我知道这是不聪明,但它是我现在
我敢肯定,当我尝试这样做,我发现某些浏览器需要外壳是正确的。看起来Laravel正在降低一切,这在技术上没问题,但可能仍然会失败。 – Evert
@Evert我注意到了,并考虑使用内置的php'header()'函数。但问题仍然存在。 – klvmungai
那很奇怪。你是否也确保你发送所有这些头部的GET,PUT,DELETE和POST请求?它是必需的.. – Evert