76 lines
2.0 KiB
PHP
76 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* 商业使用授权协议
|
|
*
|
|
* Copyright (c) 2025 [云泽网]. 保留所有权利.
|
|
*
|
|
* 本软件仅供评估使用。任何商业用途必须获得书面授权许可。
|
|
* 未经授权商业使用本软件属于侵权行为,将承担法律责任。
|
|
*
|
|
* 授权购买请联系: 357099073@qq.com
|
|
* 官方网站: https://www.yunzer.cn
|
|
*
|
|
* 评估用户须知:
|
|
* 1. 禁止移除版权声明
|
|
* 2. 禁止用于生产环境
|
|
* 3. 禁止转售或分发
|
|
*/
|
|
|
|
namespace app\middleware;
|
|
|
|
use think\Request;
|
|
use think\Response;
|
|
|
|
/**
|
|
* CORS跨域中间件
|
|
*/
|
|
class Cors
|
|
{
|
|
public function handle(Request $request, \Closure $next)
|
|
{
|
|
// 处理预检请求
|
|
if ($request->isOptions()) {
|
|
return $this->handlePreflight();
|
|
}
|
|
|
|
// 处理实际请求
|
|
$response = $next($request);
|
|
|
|
// 添加CORS头
|
|
return $this->addCorsHeaders($response);
|
|
}
|
|
|
|
/**
|
|
* 处理预检请求
|
|
*/
|
|
private function handlePreflight()
|
|
{
|
|
$response = Response::create('', 'html', 200);
|
|
|
|
return $this->addCorsHeaders($response);
|
|
}
|
|
|
|
/**
|
|
* 添加CORS头
|
|
*/
|
|
private function addCorsHeaders(Response $response)
|
|
{
|
|
$origin = request()->header('origin', '*');
|
|
|
|
// 在生产环境中,应该验证允许的域名
|
|
// 这里为了开发方便,允许所有域名
|
|
$allowedOrigin = $origin;
|
|
|
|
$response->header([
|
|
'Access-Control-Allow-Origin' => $allowedOrigin,
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS, PATCH',
|
|
'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization, Cache-Control, X-CSRF-Token, X-Token, token, Token',
|
|
'Access-Control-Allow-Credentials' => 'true',
|
|
'Access-Control-Max-Age' => '86400', // 24小时
|
|
'Access-Control-Expose-Headers' => 'Authorization, Content-Disposition',
|
|
]);
|
|
|
|
return $response;
|
|
}
|
|
}
|