rambo 1 year ago
parent
commit
77df2e5b28
4 changed files with 71 additions and 2 deletions
  1. 1 1
      app/api/middleware.php
  2. 5 0
      app/middleware.php
  3. 65 0
      app/middleware/AllowCrossDomain.php
  4. 0 1
      public/index.php

+ 1 - 1
app/api/middleware.php

@@ -7,5 +7,5 @@ return [
     // \think\middleware\LoadLangPack::class,
     // Session初始化
      \think\middleware\SessionInit::class,
-     \think\middleware\AllowCrossDomain::class,
+    //  \think\middleware\AllowCrossDomain::class,
 ];

+ 5 - 0
app/middleware.php

@@ -0,0 +1,5 @@
+<?php
+// 全局中间件定义文件
+return [
+     app\middleware\AllowCrossDomain::class,
+];

+ 65 - 0
app/middleware/AllowCrossDomain.php

@@ -0,0 +1,65 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Administrator
+ * Date: 2021/4/9
+ * Time: 17:51
+ */
+declare (strict_types = 1);
+
+namespace app\middleware;
+
+use Closure;
+use think\Config;
+use think\Request;
+use think\Response;
+
+class AllowCrossDomain
+{
+
+    protected $cookieDomain;
+
+    // header头配置
+    protected $header = [
+        'Access-Control-Allow-Credentials' => 'true',
+        'Access-Control-Max-Age'           => 1800,
+        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
+        'Access-Control-Allow-Origin'   =>'*'
+        // 'Access-Control-Allow-Headers'     => '*',
+    ];
+
+
+    /**
+     * AllowCrossDomain constructor.
+     * @param Config $config
+     */
+    public function __construct(Config $config)
+    {
+        // $this->cookieDomain = $config->get('cookie.domain', '');
+    }
+
+    /**
+     * 允许跨域请求
+     * @access public
+     * @param Request $request
+     * @param Closure $next
+     * @param array   $header
+     * @return Response
+     */
+    public function handle($request, Closure $next, ?array $header = [])
+    {
+        $header = !empty($header) ? array_merge($this->header, $header) : $this->header;
+
+        // if (!isset($header['Access-Control-Allow-Origin'])) {
+        //     $origin = $request->header('origin');
+
+        //     if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) {
+        //         $header['Access-Control-Allow-Origin'] = $origin;
+        //     } else {
+        //         $header['Access-Control-Allow-Origin'] = '*';
+        //     }
+        // }
+
+        return $next($request)->header($header);
+    }
+}

+ 0 - 1
public/index.php

@@ -11,7 +11,6 @@
 
 // [ 应用入口文件 ]
 namespace think;
-header('Access-Control-Allow-Origin:*');
 $i=strpos($_SERVER['REQUEST_URI'],'/bmap/');
 if($i!==false){
     if(isset($_SERVER["HTTP_REFERER"])){