Laravel cors 'Access-Control-Allow-Origin'

2020-02-07 06:01发布

问题:

I am new to Laravel.

I tried https://github.com/barryvdh/laravel-cors.

When I add

header('Access-Control-Allow-Origin: *');

in my public/index.php, it does not add the Content-Type in the response.

When I add

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, Content-Type');

It does not add Access-Control-Allow-Origin.

I am very confused by all various solutions I find on internet. How exactly should I go about this?

回答1:

You can create a new middleware and add the headers to the response:

Run php artisan make:middleware ModifyHeadersMiddleware

Open the file ModifyHeadersMiddleware and modify the handle() method:

public function handle( $request, Closure $next )
{
    $response = $next( $request );
    $response->header( 'Access-Control-Allow-Origin', '*' );
    $response->header( 'Access-Control-Allow-Headers', 'Origin, Content-Type' );

    return $response;
}

Open app/Http/Kernel.php and in the protected $middleware array add the ModifyHeadersMiddleware class.