Laravel CORS 进入框架 v 9

ter*_*fia 5 php laravel

在 Laravel 9 之前,当我遇到错误时:

Access to XMLHttpRequest at 'http://localhost:8000/demo' from origin 'null' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

我必须安装fruitcake/laravel-cors(https://www.positronx.io/how-to-enable-cors-in-laravel/ )。

在 Laravel 9 中我找到了信息:

“将 Laravel CORS 集成到框架中 Dries Vints 将 Fruitcake/laravel-cors 包迁移到 Laravel 框架中:主要原因是我们希望消除我们所依赖的循环依赖,此外我们还消除了骨架的另一个依赖。所有代码的来源请转至 @fruitcake 的 @barryvdh。感谢您长期维护该软件包!”。

我如何在新的 Laravel 中为 url: api/list 和 api/profiles 创建 cors?

Pun*_*ash 5

app/Http/Kernel.php检查 CORS 中间件是否存在时:

protected $middleware = [
    ...
    \Illuminate\Http\Middleware\HandleCors::class,
    ...
];
Run Code Online (Sandbox Code Playgroud)

然后打开你的config/cors.php. 它的工作原理与以下完全相同fruitcake/laravel-cors

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];
Run Code Online (Sandbox Code Playgroud)