ด้วยสํานึกในพระมหากรุณาธิคุณสมเด็จพระนางเจ้าสิริกิติ์เป็นล้นพ้นอันหาที่สุดมิได้


การใช้งาน HTTP Server และ HTTP Client ใน TypeScript เบื้องต้น

บทความ เมื่อไม่กี่สัปดาห์ โดย Ninenik Narkdee
typescript

คำสั่ง การ กำหนด รูปแบบ ตัวอย่าง เทคนิค ลูกเล่น การประยุกต์ การใช้งาน เกี่ยวกับ typescript

ดูแล้ว 118 ครั้ง


ในการใช้งาน HTTP Server และ HTTP Client นั้น TypeScript ไม่ได้มีไลบรารี Core Library แบบรวมศูนย์เหมือน dart:io แต่การทำงานจะขึ้นอยู่กับสภาพแวดล้อมที่โค้ดรัน:

  1. Client: ใช้ Fetch API (มาตรฐาน Web/Node.js)

  2. Server: ใช้ Node.js http Module (หรือ Frameworks เช่น Express)

บทความนี้จะแสดงวิธีจัดการทั้ง Client และ Server ในบริบทของ TypeScript โดยเน้นที่ความปลอดภัยของชนิดข้อมูล (Type Safety)
 

1. HTTP Client: การเรียกใช้งาน API (Using fetch)

 

ในฐานะ Client (เช่น ในเบราว์เซอร์หรือ Node.js environment) TypeScript/JavaScript ใช้ Fetch API ซึ่งเป็น Global Function ในการส่ง HTTP Request

 

A. การกำหนดชนิดข้อมูล (Type Safety)

 

เราใช้ interface เพื่อกำหนดโครงสร้างของข้อมูลที่จะได้รับกลับมา (Response Body) ซึ่งเป็นหัวใจสำคัญของ TypeScript ในการจัดการ API

TypeScript
// กำหนดโครงสร้างข้อมูลที่คาดหวังจาก API
interface Post {
    userId: number;
    id: number;
    title: string;
    body: string;
}

// กำหนด Generic Function เพื่อให้รับส่งข้อมูลที่มี Type
async function fetchApi<T>(url: string, method: string = 'GET'): Promise<T> {
    const response = await fetch(url, { method });

    if (!response.ok) {
        throw new Error(`HTTP Error! Status: ${response.status}`);
    }

    // แปลง Response เป็น JSON และระบุชนิดข้อมูลด้วย <T>
    return response.json() as T;
}

 

B. ตัวอย่างการใช้งาน GET และ POST

 

เราใช้ async/await ร่วมกับ fetch เพื่อให้โค้ดมีความอ่านง่ายและเป็นลำดับ

TypeScript
async function getPostExample() {
    try {
        // ใช้ <Post> เพื่อระบุชนิดข้อมูลที่คาดหวัง
        const post: Post = await fetchApi<Post>('https://jsonplaceholder.typicode.com/posts/1');
        
        console.log(`Title: ${post.title}`); // TypeScript รู้จัก post.title
    } catch (error) {
        console.error("Fetch failed:", error);
    }
}

async function createPostExample() {
    const newPost = {
        title: 'New TS Post',
        body: 'This is body',
        userId: 1,
    };

    const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(newPost), // แปลง Object เป็น JSON String
    });

    const createdPost: Post = await response.json();
    console.log(`Created ID: ${createdPost.id}`);
}

2. HTTP Server: การสร้าง Web Server (Using Node.js)

 

สำหรับการสร้าง HTTP Server ใน TypeScript จะใช้ Module หลักของ Node.js ที่ชื่อว่า node:http ซึ่งจำเป็นต้องมีการ import ก่อนใช้งาน

 

A. การสร้าง Server

 

เราใช้เมธอด http.createServer() ที่รับ Callback Function ที่มีพารามิเตอร์ req (Request) และ res (Response)

TypeScript
// ต้องติดตั้ง @types/node ก่อน: npm install @types/node
import * as http from 'node:http'; 
import { IncomingMessage, ServerResponse } from 'node:http'; // Import Types

const hostname: string = '127.0.0.1';
const port: number = 3000;

// กำหนดชนิดข้อมูลให้กับ req และ res เพื่อให้ TypeScript ช่วยตรวจสอบ
const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {
    // 1. การกำหนด HTTP Status Code
    res.statusCode = 200; 

    // 2. การกำหนด Header
    res.setHeader('Content-Type', 'application/json'); 

    // 3. การจัดการ Routing (อย่างง่าย)
    if (req.url === '/hello' && req.method === 'GET') {
        const data = { message: 'Hello from TypeScript Node.js Server!' };
        res.end(JSON.stringify(data)); // ส่ง Response กลับ
    } else {
        res.statusCode = 404;
        res.end(JSON.stringify({ error: 'Not Found' }));
    }
});

// การเริ่มฟัง (Listen)
server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});


กด Like หรือ Share เป็นกำลังใจ ให้มีบทความใหม่ๆ เรื่อยๆ น่ะครับ



ทบทวนบทความที่แล้ว









เนื้อหาที่เกี่ยวข้อง



Tags:: typescript







URL สำหรับอ้างอิง










เว็บไซต์ของเราให้บริการเนื้อหาบทความสำหรับนักพัฒนา โดยพึ่งพารายได้เล็กน้อยจากการแสดงโฆษณา โปรดสนับสนุนเว็บไซต์ของเราด้วยการปิดการใช้งานตัวปิดกั้นโฆษณา (Disable Ads Blocker) ขอบคุณครับ