代码之家  ›  专栏  ›  技术社区  ›  Deepak Kumar

Laravel中dingoapi中的CORS中间件

  •  0
  • Deepak Kumar  · 技术社区  · 7 年前

    我想把cors应用到拉威尔的dingo api中。

    No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 500.
    

    我试过这个。 创建了Cors中间件。

    添加如下Cors.php

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    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')
              ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
              ->header('Access-Control-Allow-Credentials',' true');
        }
    }
    

    然后像这样修改Kernel.php。

    protected $routeMiddleware = [
            'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
            'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
            'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
            'can' => \Illuminate\Auth\Middleware\Authorize::class,
            'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
            'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
            'cors' => \App\Http\Middleware\Cors::class,
        ];
    

    现在,我想知道如何在dingoapi路由中添加中间件。 路线是这样的。

    $api->version('v1', function($api){
        $api->GET('statelist', 'App\Http\Controllers\HospitalController@statelist');
    });
    $api->version('v1', function($api){
        $api->GET('citylist', 'App\Http\Controllers\HospitalController@citylist');
    });
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Mayuri Pansuriya    7 年前

    尝试

    $api->version('v1', function ($api) {
        $api->group(['middleware' => 'cors'], function ($api) {
            $api->GET('statelist', 'App\Http\Controllers\HospitalController@statelist');
            $api->GET('citylist', 'App\Http\Controllers\HospitalController@citylist');
        });
    });
    
    推荐文章