Files
webman-buildadmin/app/process/Http.php

39 lines
1.5 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\process;
use Webman\App;
use Webman\Http\Response;
class Http extends App
{
/**
* 在父类处理前拦截 OPTIONS 预检,直接返回 CORS 头(避免预检未命中路由时无 CORS
*/
public function onMessage($connection, $request): void
{
$method = $request->method();
if (is_string($method) && strtoupper($method) === 'OPTIONS') {
$path = $request->path();
$path = is_string($path) ? trim($path, '/') : '';
$isApiOrAdmin = $path !== '' && (str_starts_with($path, 'api') || str_starts_with($path, 'admin'));
if ($isApiOrAdmin) {
$origin = $request->header('origin');
$origin = is_array($origin) ? ($origin[0] ?? '') : (is_string($origin) ? trim($origin) : '');
if ($origin === '') {
$origin = '*';
}
$headers = [
'Access-Control-Allow-Origin' => $origin,
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '1800',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, batoken, ba-user-token, think-lang',
];
$connection->send(new Response(204, $headers, ''));
return;
}
}
parent::onMessage($connection, $request);
}
}