166940d5a6
Made-with: Cursor
45 lines
1.3 KiB
PHP
45 lines
1.3 KiB
PHP
<?php
|
|
declare (strict_types = 1);
|
|
|
|
namespace app\api\middleware;
|
|
|
|
use think\Response;
|
|
|
|
/**
|
|
* API 跨域中间件
|
|
*/
|
|
class CrossDomain
|
|
{
|
|
/**
|
|
* 处理请求
|
|
* @param \think\Request $request
|
|
* @param \Closure $next
|
|
* @return mixed
|
|
*/
|
|
public function handle($request, \Closure $next)
|
|
{
|
|
// OPTIONS 请求直接返回
|
|
if ($request->method() == 'OPTIONS') {
|
|
return Response::create('', 'html', 204)
|
|
->header([
|
|
'Access-Control-Allow-Origin' => '*',
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
|
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Request-With, token',
|
|
'Access-Control-Allow-Credentials' => 'true',
|
|
]);
|
|
}
|
|
|
|
$response = $next($request);
|
|
|
|
// 设置跨域响应头
|
|
$response->header([
|
|
'Access-Control-Allow-Origin' => '*',
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
|
|
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Request-With, token',
|
|
'Access-Control-Allow-Credentials' => 'true',
|
|
]);
|
|
|
|
return $response;
|
|
}
|
|
}
|