1、配置全域性中介軟體
CORS 跨域需要服務端返回的 Response Headers
中返回允許跨域的引數。如下配置公共返回:
<?php
namespace App\Http\Middleware;
use Closure;
class CrossMiddleware
{
/**
* Handle an incoming request.
* @param $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Keep-Alive,X-Requested-With,Cache-Control,Content-Type,auth,sign,Token,Pt,Xsign,toolken,code');
$response->header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->header('Access-Control-Allow-Credentials', 'true');
$response->header('Access-Control-Max-Age', '3600');
return $response;
}
}
2、異常捕獲
因為瀏覽器會傳送 options
型別的請求,路由需要設定為此型別,但是介面過多設定起來十分麻煩。可以直接捕獲 HttpException
的 405
異常。
在 App\Exceptions\Handler
中做如下配置:
public function render($request, Throwable $exception)
{
// 如果是跨域
if ($exception instanceof HttpException && $request->method() == 'OPTIONS') {
return response()->json();
}
return parent::render($request, $exception);
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結