CORS (Cross-Origin Resource Sharing) คือกลไกของ Browser ที่อนุญาตให้เว็บจาก origin หนึ่งเรียก resource จากอีก origin ได้เมื่อ Server กำหนด header อนุญาตอย่างถูกต้อง
%%{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["ยุค Same-Origin / Browser Security"]
A["Same-Origin Policy
กันเว็บอื่นอ่านข้อมูล"]
end
subgraph Era2["ยุค API แยก Domain / Cross-Origin API"]
B["CORS Headers
allow origin"]
C["Preflight OPTIONS
ถามก่อน request จริง"]
end
subgraph Era3["ยุค Production Domains"]
D["Credentials
cookie ข้าม origin"]
E["Strict Origin List
domain จริงเท่านั้น"]
end
A --> B --> C --> D --> E
npm install cors เพิ่ม CORS Middleware ใน Expressapp.use(cors({ origin: 'http://localhost:4200' })) กำหนด origin ที่อนุญาตcors({ credentials: true }) เมื่อส่ง CookieOPTIONS ที่ Browser ส่งก่อน request จริงบางประเภทGET, POST, PUT, DELETEContent-Type, Authorization* เมื่อมี credentials| ค่า | หน้าที่ | ตัวอย่าง |
|---|---|---|
origin |
domain ที่อนุญาต | http://localhost:4200 |
credentials |
อนุญาต cookie/header credentials | true |
methods |
method ที่อนุญาต | GET,POST,PUT,DELETE |
allowedHeaders |
header ที่อนุญาต | Content-Type,Authorization |
%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#fabd2f", "primaryTextColor": "#282828", "primaryBorderColor": "#b57614", "lineColor": "#7c6f64", "secondaryColor": "#83a598", "tertiaryColor": "#b8bb26", "background": "#fbf1c7", "mainBkg": "#ebdbb2", "fontFamily": "Tahoma, sans-serif"}}}%%
sequenceDiagram
participant B as Browser / Angular
participant A as API Server / Express
B->>A: OPTIONS /api/users
A-->>B: Access-Control-Allow-Origin
B->>A: POST /api/users
A-->>B: JSON Response
// cors-server.mjs
// ตั้งค่า CORS ให้ Angular dev server เรียก API ได้
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({
origin: process.env.CLIENT_ORIGIN || 'http://localhost:4200',
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' });
});
app.listen(3000, () => console.log('CORS API on http://localhost:3000'));
// ตัวอย่างการใช้งาน:
// npm install express cors
// CLIENT_ORIGIN=http://localhost:4200 node cors-server.mjs
// Angular HttpClient request พร้อม credentials
this.http.get('/api/profile', {
withCredentials: true
});
// ตัวอย่างการใช้งาน:
// ใช้เมื่อ backend ส่ง cookie เช่น refresh token หรือ session cookie
http://localhost:4200credentials: true แล้วทดลองส่ง cookie