laravel-跨域解决

Laravel API接口跨域访问 “Access-Control-Allow-Origin”

step1-创建中间件

创建文件app/Http/Middleware/CORS.php, 将下面代码复制到文件中.

<?php
namespace App\Http\Middleware;
use Closure;

class CORS
{
    public function handle($request, Closure $next)
    {
        return $next($request)->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization,X-Requested-With');
    }
}

step2-注册中间件路由

打开文件: \app\Http\Kernel.php, 找到 protected $middleware 然后增加\App\Http\Middleware\CORS::class,

protected $middleware = [
    ...
    \App\Http\Middleware\CORS::class, //跨域访问中间件
    ...
];

相关资料

Laravel API接口跨域访问

发表评论