1
|
|
|
<?php |
2
|
|
|
// +---------------------------------------------------------------------- |
3
|
|
|
// | ThinkPHP [ WE CAN DO IT JUST THINK ] |
4
|
|
|
// +---------------------------------------------------------------------- |
5
|
|
|
// | Copyright (c) 2006~2021 http://thinkphp.cn All rights reserved. |
6
|
|
|
// +---------------------------------------------------------------------- |
7
|
|
|
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) |
8
|
|
|
// +---------------------------------------------------------------------- |
9
|
|
|
// | Author: liu21st <[email protected]> |
10
|
|
|
// +---------------------------------------------------------------------- |
11
|
|
|
declare (strict_types = 1); |
12
|
|
|
|
13
|
|
|
namespace think\middleware; |
14
|
|
|
|
15
|
|
|
use Closure; |
16
|
|
|
use think\Config; |
17
|
|
|
use think\Request; |
18
|
|
|
use think\Response; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* 跨域请求支持 |
22
|
|
|
*/ |
23
|
|
|
class AllowCrossDomain |
24
|
|
|
{ |
25
|
|
|
protected $cookieDomain; |
26
|
|
|
|
27
|
|
|
protected $header = [ |
28
|
|
|
'Access-Control-Allow-Credentials' => 'true', |
29
|
|
|
'Access-Control-Max-Age' => 1800, |
30
|
|
|
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS', |
31
|
|
|
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With', |
32
|
|
|
]; |
33
|
|
|
|
34
|
3 |
|
public function __construct(Config $config) |
35
|
|
|
{ |
36
|
3 |
|
$this->cookieDomain = $config->get('cookie.domain', ''); |
37
|
3 |
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* 允许跨域请求 |
41
|
|
|
* @access public |
42
|
|
|
* @param Request $request |
43
|
|
|
* @param Closure $next |
44
|
|
|
* @param array $header |
45
|
|
|
* @return Response |
46
|
|
|
*/ |
47
|
3 |
|
public function handle($request, Closure $next, ? array $header = []) |
48
|
|
|
{ |
49
|
3 |
|
$header = !empty($header) ? array_merge($this->header, $header) : $this->header; |
50
|
|
|
|
51
|
3 |
|
if (!isset($header['Access-Control-Allow-Origin'])) { |
52
|
3 |
|
$origin = $request->header('origin'); |
53
|
|
|
|
54
|
3 |
|
if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) { |
|
|
|
|
55
|
|
|
$header['Access-Control-Allow-Origin'] = $origin; |
56
|
|
|
} else { |
57
|
3 |
|
$header['Access-Control-Allow-Origin'] = '*'; |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
$method = $_SERVER["REQUEST_METHOD"]; |
62
|
|
|
if ($method == "OPTIONS"){ |
63
|
|
|
return Response('',200,$header); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return $next($request)->header($header); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|