Files

57 lines
1.9 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
namespace ywxapp\middleware;
/**
* AllowCrossDomain 类
*
* @author ywxapp <admin@ywxapp.cn>
*/
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);
}
}