feat: ...

This commit is contained in:
admin
2025-09-24 15:05:42 +07:00
parent 58a2fc3f5c
commit b78a95e244
13 changed files with 330 additions and 96 deletions

View File

@@ -40,7 +40,13 @@ const PORT = Number(process.env.PORT || 3001);
const NODE_ENV = process.env.NODE_ENV || 'production';
// Origin ของ Frontend (ถ้ามี Nginx ด้านหน้า ให้ใช้โดเมน/พอร์ตของ Frontend)
const FRONTEND_ORIGIN = process.env.FRONTEND_ORIGIN || 'https://dcs.mycloudnas.com'; // ใส่เช่น 'https://dcs.mycloudnas.com'
// Origin ของ Frontend (ตั้งผ่าน ENV ในแต่ละสภาพแวดล้อม; dev ใช้ localhost)
const FRONTEND_ORIGIN = process.env.FRONTEND_ORIGIN || 'https://lcbp3.mycloudnas.com';
const ALLOW_ORIGINS = [
'http://localhost:3000',
'http://127.0.0.1:3000',
FRONTEND_ORIGIN,
].filter(Boolean);
// ที่เก็บ log ภายใน container ถูก bind ไปที่ /share/Container/dms/logs/backend
const LOG_DIR = process.env.BACKEND_LOG_DIR || '/app/logs';
@@ -57,23 +63,29 @@ try {
* ========================== */
const app = express();
// หลัง Nginx/Reverse Proxy ควรเปิด trust proxy เพื่ออ่าน X-Forwarded-*
app.set('trust proxy', 1);
// CORS แบบกำหนด origin ตามรายการที่อนุญาต + อนุญาต credentials
app.use(cors({
origin(origin, cb) {
// อนุญาต server-to-server / curl ที่ไม่มี Origin
if (!origin) return cb(null, true);
return cb(null, ALLOW_ORIGINS.includes(origin));
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
exposedHeaders: ['Content-Disposition', 'Content-Length'],
}));
// จัดการ preflight ให้ครบ
app.options('*', cors({
origin(origin, cb) {
if (!origin) return cb(null, true);
return cb(null, ALLOW_ORIGINS.includes(origin));
},
credentials: true,
}));
app.use(cors({ origin: true, credentials: true }));
app.use(express.json());
app.use(cookieParser());
// CORS แบบง่าย (ต้องการละเอียดกว่านี้ใช้ cors package ได้ แต่ที่นี่ทำ manual)
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', FRONTEND_ORIGIN);
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition, Content-Length');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
// Payload limits
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));