简体   繁体   English

Laravel中Dingo API中的CORS中间件

[英]CORS Middleware in Dingo API in Laravel

I want to apply cors in dingo api in laravel. 我想在Laravel的dingo api中应用cors。 Because, I am getting this error. 因为,我收到此错误。

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.

I have tried this. 我已经试过了。 Created Cors middleware. 创建了Cors中间件。

Added like this Cors.php 像这样添加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');
    }
}

Then modified Kernel.php like this. 然后像这样修改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,
    ];

Now, I want to know how to add middleware in dingo api routes. 现在,我想知道如何在dingo api路由中添加中间件。 Routes are like this. 路线是这样的。

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

try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM