使用easyswoole框架进行开发时,往往需要我们进行跨域设置处理,这样能使我们的项目更安全的运行,但是easyswoole官方手册在进行跨域设置时还不够人性化,要么只能设置一个跨域域名,要么就设置允许所有域名进行跨域,那么我们怎么设置才能指定允许自己的多个域名进行跨域,而不是所有域名跨域呢,操作如下
//官方允许跨域操作,在EasySwooleEvent.php中注册此方法
public static function onRequest(Request $request, Response $response): bool
{
// TODO: Implement onRequest() method.
$response->withHeader('Access-Control-Allow-Origin', '*');//允许所有跨域
$response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->withHeader('Access-Control-Allow-Credentials', 'true');
$response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
if ($request->getMethod() === 'OPTIONS') {
$response->withStatus(Status::CODE_OK);
return false;
}
return true;
}
//在EasySwooleEvent.php中注册此方法
public static function onRequest(Request $request, Response $response): bool
{
// TODO: Implement onRequest() method.
// 获取跨域来源
$origin = $request->getHeader("origin");
if($origin)
{
//设置允许的来源数组
$referee = ["https://yourName1.cn","https://yourName2.cn","https://yourName3.cn"];
//判断来源进行过滤
if(!in_array($origin[0],$referee)){
return false;
}
}
//此处允许所有跨域
$response->withHeader('Access-Control-Allow-Origin', '*');
$response->withHeader('Access-Control-Allow-Methods', 'GET, POST');
$response->withHeader('Access-Control-Allow-Credentials', 'true');
$response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
if ($request->getMethod() === 'OPTIONS') {
$response->withStatus(Status::CODE_OK);
return false;
}
return true;
}