From 32ddbdabedd645696a792b8f81ca3aa519658b07 Mon Sep 17 00:00:00 2001 From: AwesomeXiangQi Date: Sun, 13 Sep 2026 13:56:00 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D:=20=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1=20CORS=20=E5=A4=84=E7=90=86=E5=AF=BC?= =?UTF-8?q?=E8=87=B4=E6=B2=B9=E7=8C=B4=E8=B7=A8=E5=9F=9F=20POST=20?= =?UTF-8?q?=E8=A2=AB=E9=A2=84=E6=A3=80=E6=8B=A6=E6=88=AA(405)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- xiangqi_bot/server.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/xiangqi_bot/server.py b/xiangqi_bot/server.py index 8d6ae6f..e05e811 100644 --- a/xiangqi_bot/server.py +++ b/xiangqi_bot/server.py @@ -58,6 +58,19 @@ class Service: 'score': score, 'note': None} +@web.middleware +async def cors_middleware(request, handler): + """油猴脚本从 https 页面跨域调用本服务: 处理 OPTIONS 预检并补 CORS 头。""" + if request.method == 'OPTIONS': + resp = web.Response(status=204) + else: + resp = await handler(request) + resp.headers['Access-Control-Allow-Origin'] = '*' + resp.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS' + resp.headers['Access-Control-Allow-Headers'] = 'Content-Type' + return resp + + def make_app(args): svc = Service(args) @@ -88,7 +101,7 @@ def make_app(args): except Exception as e: return web.json_response({'ok': False, 'error': str(e)}, status=500) - app = web.Application() + app = web.Application(middlewares=[cors_middleware]) app.router.add_get('/health', health) app.router.add_post('/bestmove', bestmove) app.on_startup.append(svc.startup)