การเชื่อมต่อ Angular Frontend กับ Node.js/Express Backend

Full-stack Integration คือการเชื่อม Angular Frontend กับ Backend API เช่น Node.js/Express โดยจัดการ URL, CORS, environment, loading state, error state และ type ที่ใช้ร่วมกันให้เป็นระบบ

Timeline/ประวัติศาสตร์

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  subgraph Era1["ยุคแยก Front/Back / Separate Apps"]
    A["Angular Dev Server
localhost:4200"] B["Express API
localhost:3000"] end subgraph Era2["ยุค Proxy/CORS / Development Integration"] C["proxy.conf.json
forward /api"] D["cors middleware
allow origin"] end subgraph Era3["ยุค Shared Contract / Type-safe Integration"] E["HttpClient Service
เรียก API"] F["Shared Types
interface ร่วมกัน"] end A --> C --> E B --> D --> E --> F

แนวคิดสำคัญ

ตารางแนวทางเชื่อมต่อ

วิธี ใช้เมื่อ ข้อดี ข้อควรระวัง
Angular proxy development ไม่ต้องเปิด CORS กว้าง ใช้เฉพาะ dev
CORS middleware dev/prod API แยก domain ควบคุม origin ได้ ตั้งค่า credentials ให้ถูก
Same domain deploy production ลดปัญหา CORS ต้อง config reverse proxy
Shared types monorepo ลด type mismatch ต้องจัด package structure

Mermaid Diagram: Integration Flow

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
flowchart LR
  A["Angular Component
หน้าจอ"] --> B["Angular API Service
HttpClient"] B --> C["/api/lessons
Proxy หรือ apiUrl"] C --> D["Express Backend
REST API"] D --> E["Database/Memory
ข้อมูล"] E --> D --> B --> A

Code Example

// proxy.conf.json
// forward request /api จาก Angular ไป Express ระหว่าง development
{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "changeOrigin": true
  }
}
// angular.json เฉพาะส่วน serve.options
{
  "serve": {
    "options": {
      "proxyConfig": "proxy.conf.json"
    }
  }
}
// lesson-api.service.ts
// Angular service สำหรับเรียก backend API
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

export interface Lesson {
  id: number;
  title: string;
}

@Injectable({ providedIn: 'root' })
export class LessonApiService {
  constructor(private http: HttpClient) {}

  getLessons(): Observable<Lesson[]> {
    return this.http.get<Lesson[]>('/api/lessons');
  }
}

// ตัวอย่างการใช้งาน:
// this.lessonApi.getLessons().subscribe(...)
// server.mjs
// Express API สำหรับให้ Angular เรียก
import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors({ origin: 'http://localhost:4200' }));

app.get('/api/lessons', (req, res) => {
  res.json([{ id: 1, title: 'Full-stack Integration' }]);
});

app.listen(3000, () => console.log('API on http://localhost:3000'));

// ตัวอย่างการใช้งาน:
// ng serve --proxy-config proxy.conf.json
// node server.mjs

วิดีโอแนะนำ

กิจกรรมท้ายบท

กลับสัปดาห์ที่ 13