1
|
|
|
<?php |
2
|
|
|
// +---------------------------------------------------------------------- |
3
|
|
|
// | ThinkPHP [ WE CAN DO IT JUST THINK ] |
4
|
|
|
// +---------------------------------------------------------------------- |
5
|
|
|
// | Copyright (c) 2006~2019 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-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS', |
30
|
|
|
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With', |
31
|
|
|
]; |
32
|
|
|
|
33
|
1 |
|
public function __construct(Config $config) |
|
|
|
|
34
|
|
|
{ |
35
|
1 |
|
$this->cookieDomain = $config->get('cookie.domain', ''); |
36
|
1 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* 允许跨域请求 |
40
|
|
|
* @access public |
41
|
|
|
* @param Request $request |
|
|
|
|
42
|
|
|
* @param Closure $next |
|
|
|
|
43
|
|
|
* @param array $header |
|
|
|
|
44
|
|
|
* @return Response |
45
|
|
|
*/ |
46
|
1 |
|
public function handle($request, Closure $next, ?array $header = []) |
47
|
|
|
{ |
48
|
1 |
|
$header = !empty($header) ? array_merge($this->header, $header) : $this->header; |
49
|
|
|
|
50
|
1 |
|
if (!isset($header['Access-Control-Allow-Origin'])) { |
51
|
1 |
|
$origin = $request->header('origin'); |
52
|
|
|
|
53
|
1 |
|
if ($origin && ('' == $this->cookieDomain || strpos($origin, $this->cookieDomain))) { |
|
|
|
|
54
|
|
|
$header['Access-Control-Allow-Origin'] = $origin; |
55
|
|
|
} else { |
56
|
1 |
|
$header['Access-Control-Allow-Origin'] = '*'; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
return $next($request)->header($header); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|