lundi 1 octobre 2018

CORS Middleware in Dingo API in Laravel

I want to apply cors in dingo api in laravel. 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.

Added like this 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.

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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire