Laravel--CORS 扩展包完美解决前后端分离应用跨域请求

概述

跨域请求的解决方案有 CORS 和 JSONP(了解更多明细可以参考这篇教程),但是 JSONP 有个致命缺点 —— 仅支持 GET 请求,所以推荐使用 CORS(Cross-origin resource sharing,跨域资源共享),何况在 Laravel 生态中已经有了 laravel-cors 这样强大的扩展包,拿来即用,只需要配置一个中间件即可上手,非常方便。
本片文章讲解两种跨域方式

1. laravel-cors

安装

在项目根目录下通过 Composer 安装扩展包:

composer require barryvdh/laravel-cors

Laravel 5.5 及以上版本支持自动包发现,无需注册服务提供者,Laravel 5.4 及以下版本需要手动在 config/app.php 中注册服务提供者:

Barryvdh\Cors\ServiceProvider::class,

使用

如果想要全局支持跨域请求,可以在 app/Http/Kernel.php 的 $middleware 数组中添加 HandleCors 中间件:

protected $middleware = [
    \Barryvdh\Cors\HandleCors::class,
]; 

如果你只想在特定路由中应用 CORS,可将其添加到对应的路由/中间件分组:

protected $middlewareGroups = [
    'web' => [
       // ...
    ],
    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

laravel 官网文档地址:https://laravelacademy.org/post/9273.html

2.自定义中间件解决跨域问题

使用 make:middleware这个 Artisan 命令创建中间件:

php artisan make:middleware CrossHttp

中间件App\Http\Middleware\CrossHttp代码如下:

header('Access-Control-Allow-Origin', '*'); //允许所有资源跨域
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json , X-Auth-Token');//允许通过的响应报头
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');//允许的请求方法
        $response->header('Access-Control-Expose-Headers', 'Authorization');//允许axios获取响应头中的Authorization
        $response->header('Allow', 'GET, POST, PATCH, PUT, OPTIONS, delete');//允许的请求方法
        $response->header('Access-Control-Allow-Credentials', 'true');//运行客户端携带证书式访问
        return $response;
    }

}

注册路由,设置中间件保护接口

分别在 protected $middleware 数组中和 protected $routeMiddleware 数组中添加我们刚才创建的那个文件class名, 使用 cors 这个别名。然后在设置它保护 api , 文件地址:\App\Http\Kernel.php

代码如下:

    protected $middlewareGroups = [
        'api' => [
            'cors',
        ],
    ];
   protected $routeMiddleware = [
        'cors' => \App\Http\Middleware\CrossHttp::class,
    ];

好了,希望能够帮助到小伙伴,今天分享一下自己在解决跨域方面的问题

你可能感兴趣的:(laravel)