在目录app\Http\Middleware\下新建CORS.php文件,内容如下:
<?php
namespace App\Http\Middleware;
use Closure;
class CORS {
/**
* 处理请求.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
//设置允许来源头信息:Access-COntrol-Allow-Origin
header("Access-Control-Allow-Origin: *");
// 设置允许请求的方法
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
if ($request->getMethod() == "OPTIONS") {
// 对于预请求返回200
return \Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
修改文件app\Http\Kernel.php:
1、在数组$middleware添加以下代码:
\App\Http\Middleware\CORS::class
2、在数组$routeMiddleware添加以下代码
'cors' => \App\Http\Middleware\CORS::class
代码里设置头信息Access-Control-Allow-Origin为*,是表示允许所有域名的请求,建议在此处修改为指定的域名。