我正在开发一个angularjs应用程序,它使用laravel作为其后端服务器.我在每次GET请求之前从laravel访问数据时遇到问题,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
Run Code Online (Sandbox Code Playgroud)
我试图通过在前过滤器中添加以下代码来回应这个问题
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);
}
Run Code Online (Sandbox Code Playgroud)
这会使用标题创建响应
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
Run Code Online (Sandbox Code Playgroud)
虽然设置了标头,但浏览器仍会抛出错误
XMLHttpRequest cannot load http://localhost/61028/index.php/api/categories. Origin http://localhost:3501 is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)
我还尝试将allow origin设置为请求标头中显示的原点,如下所示
$origin=Request::header('origin');
//then within the headers
'Access-Control-Allow-Origin' =>' '.$origin[0],
Run Code Online (Sandbox Code Playgroud)
仍然是同样的错误我做错了什么?任何帮助是极大的赞赏.
我目前正在使用一个非常难看的黑客,当我收到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 <taylorotwell@gmail.com>
* @link http://laravel.com
*/
Run Code Online (Sandbox Code Playgroud)
我还必须将allow-origin标头添加到before过滤器.
我知道这不聪明,但它是我现在唯一的解决方案
这是针对您关于上述问题的问题。你没有提到laravel和angularJS的版本。我假设你正在使用最新的 angularJS 和 Laravel。我还假设,角度托管在http://localhost:3501上,laravel 托管在http://localhost上 ,只需按照以下步骤操作即可。
将以下代码块放入 laravel 的 /public/.htaccess 文件中
Header set Access-Control-Allow-Origin "http://localhost:3501"
Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Credentials "true"
Run Code Online (Sandbox Code Playgroud)将以下行放入角度配置中
$httpProvider.defaults.withCredentials = true;
Run Code Online (Sandbox Code Playgroud)切勿使用*作为通配符。Lavel 无法识别会话管理的域。因此,将http://localhost:3501设置为Access-Control-Allow-Origin 的完整域名。我想这些会对你有所帮助。