Allow No 'Access-Control-Allow-Origin' header is present

后台使用laravel框架,前端请求数据报错 Allow No 'Access-Control-Allow-Origin' header is present 

解决办法:

一、在App\Http\Middleware目录下新建Cors.php

headers->add($headers);

        return $response;
    }
}

二、在项目配置文件config\star.php 文件中新增跨域的配置信息
/*
    |--------------------------------------------------------------------------
    | CORS跨域配置
    |--------------------------------------------------------------------------
    |
    */
    'cors' => [
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Authorization',
        'Access-Control-Allow-Methods' => 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE',
    ],

三、讲Cros.php中间件加入到App\Http\Kernel.php中
protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\Cors::class,
    ];

以上是正常请求,为了处理异常请求的返回,在App\Exceptions\Hander.php中增加header信息

$headers = config('star.cors', []);

$response->headers->add($headers);

你可能感兴趣的:(laravel)