Browse Source

跨域问题

rambo 1 year ago
parent
commit
2f73e9b027
3 changed files with 2 additions and 78 deletions
  1. 2 1
      app/api/middleware.php
  2. 0 13
      app/middleware.php
  3. 0 64
      app/middleware/AllowCrossDomain.php

+ 2 - 1
app/api/middleware.php

@@ -6,5 +6,6 @@ return [
     // 多语言加载
     // \think\middleware\LoadLangPack::class,
     // Session初始化
-     \think\middleware\SessionInit::class
+     \think\middleware\SessionInit::class,
+     \think\middleware\AllowCrossDomain::class,
 ];

+ 0 - 13
app/middleware.php

@@ -1,13 +0,0 @@
-<?php
-// 全局中间件定义文件
-return [
-    // 全局请求缓存
-    // \think\middleware\CheckRequestCache::class,
-    // 多语言加载
-    // \think\middleware\LoadLangPack::class,
-    // Session初始化
-    // \think\middleware\SessionInit::class
-    // 
-    // 跨域请求
-    app\middleware\AllowCrossDomain::class
-];

+ 0 - 64
app/middleware/AllowCrossDomain.php

@@ -1,64 +0,0 @@
-<?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-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With,token',
-    ];
-
-
-    /**
-     * 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);
-    }
-}