我正在開發一個使用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