Files
Sliverkiss-GoodNight/_worker.js
2024-12-10 15:17:35 +08:00

38 lines
1.1 KiB
JavaScript
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.
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'
}
});
}