// +---------------------------------------------------------------------- namespace ywxapp\middleware; /** * AllowCrossDomain 类 * * @author ywxapp */ class AllowCrossDomain { public function handle($request, \Closure $next) { $origin = $request->header('Origin') ?: ''; // 允许的域名列表(根据实际情况修改) $allowedOrigins = [ 'http://localhost', 'http://localhost:3000', 'http://localhost:5173', 'http://127.0.0.1', 'http://127.0.0.1:3000', 'https://your-production-domain.com' ]; // 检查来源是否允许 if (in_array($origin, $allowedOrigins)) { header("Access-Control-Allow-Origin: $origin"); header('Access-Control-Allow-Credentials: true'); } // 明确允许的请求头(必须包含 content-type) header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, X-CSRF-TOKEN'); // 允许的方法 header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS'); // 预检请求直接返回 if ($request->method() == 'OPTIONS') { header('Access-Control-Max-Age: 86400'); // 24小时缓存 header('Content-Type: text/plain; charset=UTF-8'); header('Content-Length: 0'); return response()->code(204); } return $next($request); } }