2015-11-04 64 views
4

我正在按照本教程設置使用Laravel和Angular的令牌認證。認證中的Laravel角度CORS問題

https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps

這工作得很好,但是當我主持Laravel(作爲後端)分開,並在另一個域角前端,我得到的foolowing錯誤控制檯: -

XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate. 
Response to preflight request doesn't pass access control check: The 
'Access-Control-Allow-Origin' header contains multiple values '*, *', but 
only one is allowed. Origin 'http://jotdotfrontend.mysite.com' is 
therefore not allowed access. 

我已經放在一個在Laravel的CORS中間件,它對簡單的路由工作正常。

class Cors 
{ 
/** 
* Handle an incoming request. 
* 
* @param \Illuminate\Http\Request $request 
* @param \Closure $next 
* @return mixed 
*/ 
public function handle($request, Closure $next) 
{ 
    return $next($request)->header('Access-Control-Allow-Origin', '*')- >header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); 
} 

} 

如何添加CORS中間件這樣的: -

Route::group(['prefix' => 'api', 'middleware' => 'cors'], function() 
{ 
    Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]); 
    Route::post('authenticate', '[email protected]'); 
}); 

添加它旁邊[ '前綴'=> 'API']沒有解決的問題。

感謝

+0

可以更新路由例子來告訴你如何添加的中間件路由組定義? –

+0

@watcher - 我更新了它,還有另一種方式,但它仍然無效 –

回答

2

我覺得你的問題是,你的中間件是最有可能表現得像一個「後」的中間件,因此之前它返回到客戶端沒有修改要求。相反,它會在發送之後修改請求,這對您沒有任何好處。

嘗試修改您的handle功能是這樣的:

public function handle($request, Closure $next) 
{ 
    $request->header('Access-Control-Allow-Origin', '*'); 
    $request->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); 
    $request->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); 

    return $next($request); 
} 
+0

出現錯誤 - 在字符串上調用成員函數標頭()。檢查它 –

+0

看看更新是否適合你 –

+0

是這解決了頭問題,但仍然控制檯給出錯誤 - 「在預檢響應中,訪問控制 - 允許頭部不允許請求頭字段內容類型。 –