jh-admin/app/middleware/AllowOriginMiddleware.php

40 lines
1.2 KiB
PHP

<?php
namespace app\middleware;
use app\Request;
use think\exception\HttpResponseException;
use think\facade\Config;
use think\Response;
/**
* 跨域中间件
* Class AllowOriginMiddleware
* @package app\http\middleware
*/
class AllowOriginMiddleware extends BaseMiddleware
{
/**
* header头
* @var array
*/
protected $header = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Headers' => 'X-Token, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,Form-type,Referer,Connection,Content-Length,Host,Origin,Authorization,Authori-zation,Accept,Accept-Encoding',
'Access-Control-Allow-Methods' => 'GET,POST,PATCH,PUT,DELETE,OPTIONS',
'Access-Control-Max-Age' => '1728000'
];
public function before(Request $request)
{
$origin = $request->header('origin');
if ($request->method(true) == 'OPTIONS') {
throw new HttpResponseException(Response::create()->code(200)->header($this->header));
}else{
$this->header['Access-Control-Allow-Origin'] = $origin;
}
}
public function after(Response $response)
{
$response->header($this->header);
}
}