vr-shopxo-plugin/shopxo/app/middleware/CorsMiddleware.php

54 lines
1.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
// +----------------------------------------------------------------------
// | ShopXO 国内领先企业级B2C免费开源电商系统
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2099 http://shopxo.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/mit-license.php )
// +----------------------------------------------------------------------
// | Author: Devil
// +----------------------------------------------------------------------
declare(strict_types=1);
namespace app\middleware;
use Closure;
use think\Request;
use think\Response;
/**
* CORS 跨域中间件
*
* 在请求进入控制器之前设置 CORS 响应头,确保即使控制器中调用了 exit()
* (如 Common::IsLogin 鉴权失败),浏览器也能收到正确的跨域头。
*
* OPTIONS 预检请求直接返回 204不进入业务逻辑。
*/
class CorsMiddleware
{
/**
* 处理请求
* @access public
* @param Request $request
* @param Closure $next
* @return Response
*/
public function handle(Request $request, Closure $next): Response
{
// 先设置 CORS 响应头 — 即使在后续流程中发生 exit()
// 这些头部也已经被 PHP 排队,会随响应一起发送
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: DNT,User-Agent,Cache-Control,Content-Type,ajax,Authorization,token');
header('Access-Control-Max-Age: 86400');
// OPTIONS 预检请求直接拦截,返回 204 No Content
// 避免进入控制器触发 IsLogin 等鉴权逻辑
if ($request->method() === 'OPTIONS') {
return response('', 204);
}
return $next($request);
}
}