From a94a33f21e6c93032e7a9d68b1720080f803a923 Mon Sep 17 00:00:00 2001 From: Sliverkiss <1393579810@qq.com> Date: Tue, 10 Dec 2024 15:17:35 +0800 Subject: [PATCH] Create _worker.js --- _worker.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 _worker.js diff --git a/_worker.js b/_worker.js new file mode 100644 index 0000000..3992f7b --- /dev/null +++ b/_worker.js @@ -0,0 +1,37 @@ +addEventListener('fetch', event => { + event.respondWith(handleRequest(event.request)); +}); + +async function handleRequest(request) { + try { + + const url = new URL(request.url); + + if (url.pathname === "/query/hello"&&request.method=="GET") { + if(!requestBody?.data) throw new Error("body缺少所需要的data"); + return jsonResponse({result:"Hello World"}, 200); + } + + if (url.pathname === "/api/getBody"&&request.method=="POST") { + const requestBody = await request.json(); + return jsonResponse({result:requestBody}, 200); + } + + throw new Error("404 not found"); + } catch (error) { + // 如果请求目标地址时出现错误,返回带有错误消息的响应和状态码 500(服务器错误) + return jsonResponse({ + error: error.message + }, 500); + } +} + +// 返回 JSON 格式的响应 +function jsonResponse(data, status) { + return new Response(JSON.stringify(data), { + status: status, + headers: { + 'Content-Type': 'application/json; charset=utf-8' + } + }); +}