2015-11-04 65 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

是这解决了头问题,但仍然控制台给出错误 - “在预检响应中,访问控制 - 允许头部不允许请求头字段内容类型。 –