cors-configuration
БесплатноБез исполняемых скриптовНе проверенConfigures Cross-Origin Resource Sharing with proper headers, preflight handling, and security best practices. Use when users request "CORS setup"…
от patricio0312rev★ 64 звезды на GitHubОб этом скилле
CORS Configuration
Configure secure Cross-Origin Resource Sharing for APIs and web applications.
Core Workflow
- Identify origins: Define allowed origins
- Configure headers: Set CORS response headers
- Handle preflight: OPTIONS request handling
- Set credentials: Cookie and auth handling
- Limit methods: Allowed HTTP methods
- Test configuration: Verify CORS works
CORS Headers Reference
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization, X-Request-ID
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 86400
Access-Control-Expose-Headers: X-Request-ID, X-RateLimit-Remaining
Express.js Configuration
Basic CORS
// middleware/cors.ts
import cors from 'cors';
import { Express } from 'express';
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com',
];
// Add development origins
if (process.env.NODE_ENV === 'development') {
allowedOrigins.push('http://localhost:3000');
allowedOrigins.push('http://localhost:5173');
}
export function configureCors(app: Express) {
app.use(cors({
origin: (origin, callback) => {
// Allow requests with no origin (mobile apps, Postman)
if (!origin) {
return callback(null, true);
}
if (allowedOrigins.includes(origin)) {
return callback(null, true);
}
callback(new Error('Not allowed by CORS'));
},
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'Authorization',
'X-Request-ID',
'X-CSRF-Token',
],
exposedHeaders: [
'X-Request-ID',
'X-RateLimit-Limit',
'X-RateLimit-Remaining',
],
credentials: true,
maxAge: 86400, // 24 hours
preflightContinue: false,
optionsSuccessStatus: 204,
}));
}
Manual CORS Middleware
// middleware/manual-cors.ts
import { Request, Response, NextFunction } from 'express';
interface CorsOptions {
origins: string[];
methods: string[];
allowedHeaders: string[];
exposedHeaders: string[];
credentials: boolean;
maxAge: number;
}
const defaultOptions: CorsOptions = {
origins: [],
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: [],
credentials: false,
maxAge: 86400,
};
export function createCorsMiddleware(options: Partial<CorsOptions> = {}) {
const config = { ...defaultOptions, ...options };
return (req: Request, res: Response, next: NextFunction) => {
const origin = req.headers.origin;
// Check if origin is allowed
if (origin && config.origins.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
} else if (config.origins.includes('*')) {
res.setHeader('Access-Control-Allow-Origin', '*');
}
// Set other CORS headers
res.setHeader('Access-Control-Allow-Methods', config.methods.join(', '));
res.setHeader('Access-Control-Allow-Headers', config.allowedHeaders.join(', '));
if (config.exposedHeaders.length > 0) {
res.setHeader('Access-Control-Expose-Headers', config.exposedHeaders.join(', '));
}
if (config.credentials) {
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
res.setHeader('Access-Control-Max-Age', String(config.maxAge));
// Handle preflight request
if (req.method === 'OPTIONS') {
res.status(204).end();
return;
}
next();
};
}
Route-Specific CORS
// routes/api.ts
import { Router } from 'express';
import cors from 'cors';
const router = Router();
// Public endpoints - allow any origin
const publicCors = cors({
origin: '*',
methods: ['GET'],
});
// Private endpoints - restrict origin
const privateCors = cors({
origin: ['https://app.example.com'],
credentials: true,
});
// Webhook endpoints - specific origins
const webhookCors = cors({
origin: ['https://stripe.com', 'https://github.com'],
methods: ['POST'],
});
router.get('/public/data', publicCors, publicDataHandler);
router.post('/private/data', privateCors, privateDataHandler);
router.post('/webhooks/stripe', webhookCors, stripeWebhookHandler);
export default router;
Next.js Configuration
Middleware CORS
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
const allowedOrigins = [
'https://app.example.com',
'https://admin.example.com',
];
if (process.env.NODE_ENV === 'development') {
allowedOrigins.push('http://localhost:3000');
}
export function middleware(request: NextRequest) {
const origin = request.headers.get('origin');
const isApiRoute = request.nextUrl.pathname.startsWith('/api');
// Only apply CORS to API routes
if (!isApiRoute) {
return NextResponse.next();
}
// Handle p
Установить cors-configuration в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл cors-configuration?
Configures Cross-Origin Resource Sharing with proper headers, preflight handling, and security best practices. Use when users request "CORS setup", "cross-origin requests", "API CORS", "preflight requests", or "CORS headers".
Как установить скилл cors-configuration?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл cors-configuration запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic