Laravel的“访问控制允许来源"和“访问控制允许标题"

Laravel的“访问控制允许来源

问题描述:

我是Laravel的新手.

I am new to Laravel.

我尝试了 https://github.com/barryvdh/laravel-cors .

当我添加

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

在我的public/index.php中,它没有在响应中添加Content-Type.

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

当我添加

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

它不添加Access-Control-Allow-Origin.

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?

您可以创建一个新的中间件并将标头添加到响应中:

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

运行php artisan make:middleware ModifyHeadersMiddleware

打开文件 ModifyHeadersMiddleware 并修改handle()方法:

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;
}

打开 app/Http/Kernel.php ,然后在protected $middleware数组中添加 ModifyHeadersMiddleware 类.

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