swoole使用CORS方式解决跨域
文档说明: 只记录关键地方; 文档创建时间:2023-08-06;
目标:使用CORS 方式解决跨域
备注: 常用到的功能记录一下,方便使用
<?php
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Coroutine\Http\Server;
use function Swoole\Coroutine\run;
run(function () {
$server = new Server('0.0.0.0', 9502, false);
$server->handle('/', function (Request $request, Response $response) {
$response->header('Content-Type', 'application/json; charset=utf-8');
$response->header('access-control-allow-credentials', 'true');
$response->header('access-control-allow-methods', 'GET,HEAD,POST,OPTIONS');
$response->header('access-control-allow-headers', 'content-type,Authorization');
$response->header('Access-Control-Allow-Private-Network', 'true');
$origin = empty($request->header['origin']) ? '*' : $request->header['origin'];
$response->header('access-control-allow-origin', $origin);
$request_method = empty($request->header['request_method']) ? '' : $request->header['request_method'];
if ($request_method == "OPTIONS") {
$response->status(200);
$response->end();
return null;
}
$result = [];
try {
$result = [
'code' => 200,
"msg" => 'success',
"data" => []
];
} catch (\RuntimeException $e) {
$result = ["code" => 500, 'msg' => 'system error' . $e->getMessage()];
}
$response->end(json_encode($result, JSON_UNESCAPED_UNICODE));
});
$server->start();
});