【问题标题】:Why Laravel middleware works for single routes but not group of routes为什么 Laravel 中间件适用于单个路由而不适用于一组路由
【发布时间】:2016-02-07 16:03:19
【问题描述】:

我添加了一个 CORS 中间件,它适用于单个路由:-

Route::get('example', ['middleware' => 'cors', function(){
    return Response::json(array('name' => 'Steve Jobs', 'company' => 'Apple'));
}]);

但是当我将它应用于路由组时,它会在控制台中出现错误:-

(index):1 XMLHttpRequest cannot load http://jotdot.mysite.com/api/authenticate. 
Response to preflight request doesn't pass access control 
check: No 'Access-Control-Allow-Origin' header is present on 
the requested  resource. Origin 'http://jotdotfrontend.mysite.com' is
therefore not allowed access.

我的路线组:-

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

Cors.php

class CORS
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
    return $next($request);
}
}

我正在关注https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps 并尝试在不同的域上设置后端和前端。

谢谢

【问题讨论】:

    标签: laravel laravel-5 cross-domain cors middleware


    【解决方案1】:

    问题是基于路由的中间件从未应用于OPTIONS 请求自动生成的基于resource 的路由(因为Route::resource(...) 不会为options 方法生成路由?)。

    所以,把你的 cors 中间件放在 app/Http/Kernel.php 的全局中间件组中,就在 VerifyCsrfToken 中间件之前:

    /**
     * The application's global HTTP middleware stack.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Ankh\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\CORS::class, // here it is
        \App\Http\Middleware\VerifyCsrfToken::class,
    ];
    

    并从routes.php 中完全删除它,例如:

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

    【讨论】:

      【解决方案2】:

      你可以试试这个:

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

      【讨论】:

      • @StacyJ 我认为问题在于当您尝试发送 POST 请求时,Laravel 将验证 CsrfToken。看看Laravel Csrf protection。您需要在line 20Kernel.php 文件中禁用此中间件以解决此问题。
      【解决方案3】:

      这样试试,

      Route::group([ 'prefix' => 'api', 'middleware' => 'App\Http\Middleware\CORS'], function() {
           Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
           Route::post('authenticate', 'AuthenticateController@authenticate');
      
      });
      

      【讨论】:

      • 如何将中间件添加到组内的各个路由中?
      【解决方案4】:

      您的原始标头不在您的标头数组中。不要使用 header() 设置原始标头,而是尝试将其与其他访问控制标头一起添加,如下所示:

      // ALLOW OPTIONS METHOD
      $headers = [
          'Access-Control-Allow-Origin'=> '*',
          'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
          'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
      ];
      

      【讨论】:

        猜你喜欢
        • 2017-08-06
        • 2019-10-05
        • 2020-11-12
        • 2016-02-02
        • 2017-07-04
        • 1970-01-01
        • 2012-12-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多