CORS Configuration (CORS)
CORS Configuration: تنظیم CORS در Express.js 🌐
CORS (Cross-Origin Resource Sharing) برای اجازه دادن به frontend برای دسترسی به API استفاده میشه!
نصب و استفاده:
// نصب
// npm install cors
const express = require('express');
const cors = require('cors');
const app = express();
// استفاده ساده (اجازه به همه origins)
app.use(cors());
// یا با options
app.use(cors({
origin: 'http://localhost:3000',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
Multiple Origins:
const cors = require('cors');
const allowedOrigins = [
'http://localhost:3000',
'http://localhost:3001',
'https://myapp.com'
];
app.use(cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));
💡 نکته: CORS برای امنیت مهمه! فقط origins مورد اعتماد رو allow کنید!
✅ یاد گرفتید: CORS برای cross-origin requests ضروریه!
آماده رفتن به درس بعدی هستید؟
این درس را به پایان رساندید و میتوانید به درس بعدی بروید.