laravel全域性中介軟體解決ajax請求跨域問題
阿新 • • 發佈:2018-12-17
定義中介軟體CorsMiddleware
定義位置:
app/Http/Middleware/CorsMiddleware.php
CorsMiddleware內容
<?php namespace App\Http\Middleware; use Closure; class CorsMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if ($request->isMethod('OPTIONS')) { $response = response('', 200); } else { $response = $next($request); } if (!method_exists($response, 'header')) { return $response; } $response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS'); $response->header( 'Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With, Token' ); $response->header('Access-Control-Allow-Origin', '*'); $response->header('Access-Control-Max-Age', 86400); return $response; } }
在app/Http/Kernel.php檔案的$middleware中新增這個中介軟體
protected $middleware = [
.....
\App\Http\Middleware\CorsMiddleware::class
];