HTTP路由器
更新時間 2023-12-04 20:31:29
最近更新時間: 2023-12-04 20:31:29
分享文章
本文介紹如何根據不同的HTTP路由,響應對應內容。
根據不同的HTTP路由,響應對應內容。
示例代碼
addEventListener("fetch", (event) => {
event.respondWith(
handleRequest(event.request).catch(
(err) => new Response(err.stack, { status: 500 })
)
);
});
async function handleRequest(request) {
const { pathname } = new URL(request.url);
if (pathname.startsWith("/api")) {
return new Response(JSON.stringify({ pathname }), {
headers: { "Content-Type": "application/json" },
});
}
if (pathname.startsWith("/status")) {
const httpStatusCode = Number(pathname.split("/")[2]);
return Number.isInteger(httpStatusCode)
? fetch("//http.cat/" + httpStatusCode)
: new Response("That's not a valid HTTP status code.");
}
return new Response("This is a http router example!");
}
示例預覽
在瀏覽器地址欄中輸入匹配到HTTP路由的URL,即可預覽示例效果。
