【问题标题】:CORS Middleware in Dingo API in LaravelLaravel 中 Dingo API 中的 CORS 中间件
【发布时间】:2018-10-01 13:03:07
【问题描述】:

我想在 laravel 的 dingo api 中应用 cors。 因为,我收到了这个错误。

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,
    ];

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

$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');
});

【问题讨论】:

    标签: php laravel laravel-5


    【解决方案1】:

    试试

    $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');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-15
      • 2018-11-07
      • 2018-06-28
      • 2016-06-16
      • 2016-03-22
      • 2016-07-22
      • 2016-03-07
      • 1970-01-01
      • 2016-01-30
      相关资源
      最近更新 更多