Skip to content

يبدأ هذا خادم HTTP يستمع على المنفذ 3000. يوضح التوجيه الأساسي مع عدد من الاستجابات الشائعة ويتعامل أيضًا مع بيانات POST من النماذج القياسية أو كـ JSON.

راجع Bun.serve للحصول على التفاصيل.

ts
const server = Bun.serve({
  async fetch(req) {
    const path = new URL(req.url).pathname;

    // الرد بـ text/html
    if (path === "/") return new Response("مرحبًا بك في Bun!");

    // إعادة توجيه
    if (path === "/abc") return Response.redirect("/source", 301);

    // إرسال ملف (في هذه الحالة، *هذا* الملف)
    if (path === "/source") return new Response(Bun.file(import.meta.path));

    // الرد بـ JSON
    if (path === "/api") return Response.json({ some: "buns", for: "you" });

    // استقبال بيانات JSON لطلب POST
    if (req.method === "POST" && path === "/api/post") {
      const data = await req.json();
      console.log("تم استلام JSON:", data);
      return Response.json({ success: true, data });
    }

    // استقبال بيانات POST من نموذج
    if (req.method === "POST" && path === "/form") {
      const data = await req.formData();
      console.log(data.get("someField"));
      return new Response("Success");
    }

    // 404s
    return new Response("Page not found", { status: 404 });
  },
});

console.log(`Listening on ${server.url}`);

Bun بواسطة www.bunjs.com.cn تحرير