angularjs – 身份验证中的Laravel Angular CORS问题

我正在按照本教程使用Laravel和Angular设置使用令牌的身份验证.

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

这很好但是当我分别托管Laravel(作为后端)和另一个域上的Angular前端时,我在控制台中遇到了愚蠢的错误: –

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', 'AuthenticateController@authenticate');
});

在[‘prefix’=>旁边添加它’api’]并没有解决问题.

谢谢

最佳答案 我认为您的问题是您的中间件最有可能像“后”中间件,因此在返回客户端之前不会修改请求.相反,它会在发送请求后修改请求,这对您没有任何好处.

尝试修改你的句柄功能,如下所示:

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);
}
点赞