doge пре 2 месеци
родитељ
комит
8d3b021990
2 измењених фајлова са 20 додато и 2 уклоњено
  1. 6 1
      app/common.php
  2. 14 1
      app/common/middleware/Cors.php

+ 6 - 1
app/common.php

@@ -73,6 +73,12 @@ function error($msg, $code = 502)
  */
 function shutdown($msg, $code = 401)
 {
+    $headers = \app\common\middleware\Cors::headers(request());
+    foreach ($headers as $name => $value) {
+        header($name . ': ' . $value);
+    }
+    header('Content-Type: application/json; charset=utf-8');
+
     exit(json_encode(['code' => $code, 'msg' => $msg?:lang('system.forbidden'), 'data' => []]));
 }
 
@@ -1496,4 +1502,3 @@ function queuePush($data, $delay = 0, $job = "Work", $queue = "im")
         return false;
     }
 }
-

+ 14 - 1
app/common/middleware/Cors.php

@@ -9,7 +9,13 @@ use think\Response;
  */
 class Cors
 {
-    public function handle($request, Closure $next)
+    /**
+     * 生成统一的跨域响应头。
+     *
+     * 除中间件正常响应外,shutdown() 这类提前终止的响应也需要复用,
+     * 否则浏览器会把真实的登录/权限错误误报为 CORS 错误。
+     */
+    public static function headers($request): array
     {
         $origin = $request->header('origin', '');
         $origin = trim(str_replace(["\r", "\n"], '', $origin));
@@ -53,6 +59,13 @@ class Cors
             $headers['Access-Control-Allow-Private-Network'] = 'true';
         }
 
+        return $headers;
+    }
+
+    public function handle($request, Closure $next)
+    {
+        $headers = self::headers($request);
+
         if (strtoupper($request->method()) === 'OPTIONS') {
             return Response::create('', 'html', 204)->header($headers);
         }