XY BLOG

XY的BLOG

laravel 跨域 fruitcake/laravel-cors

Published on in Posts
Updated on
Short link: https://b.xyzt07.cn/s/1a
Share this post
A ⇄ 文
⚠️ This entry is already over one year old. It may no longer be up to date. Opinions may have changed.

下载安装

composer require fruitcake/laravel-cors

使用 发布配置文件

php artisan vendor:publish --tag="cors"

自定义header头时,比如:Authorization、Content-type时,要设置allowed_headers来包含这些header信息,也可以设置为[*]以允许所有请求haeder信息 如果要精确设置请求白名单,则必须将白名单包含进allowed_methods所对应的数组

<?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

allowed_origins allowed_headers 和 allowed_methods可以设置成[’*’] 来允许所有值

允许所有api跨域请求,添加HandleCors中间件到app/Http/Kernel.php的$middleware属性里:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

在$routeMiddleware属性里添加:

protected $routeMiddleware = [
    'cors' => \Fruitcake\Cors\HandleCors::class,
]

在 config/app.php 的 providers里添加服务提供者:

'providers' => [
    ...
    Fruitcake\Cors\CorsServiceProvider::class,
]

在 routes/api.php里添加路由cors中间件:

Route::middleware('cors')->group(function () {

});