import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' /** 允许的跨域来源(管理端独立项目、本地开发) */ const ALLOWED_ORIGINS = [ 'http://localhost:5174', // soul-admin 开发 'http://127.0.0.1:5174', 'https://soul.quwanzhi.com', // 若管理端与 API 同域则不需要,预留 ] function getCorsHeaders(origin: string | null) { const allowOrigin = origin && ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0] return { 'Access-Control-Allow-Origin': allowOrigin, 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', 'Access-Control-Allow-Credentials': 'true', 'Access-Control-Max-Age': '86400', } } export function middleware(req: NextRequest) { const origin = req.headers.get('origin') || '' const isApi = req.nextUrl.pathname.startsWith('/api/') if (!isApi) { return NextResponse.next() } const corsHeaders = getCorsHeaders(origin || 'http://localhost:5174') // 预检请求:直接返回 200 + CORS 头 if (req.method === 'OPTIONS') { return new NextResponse(null, { status: 204, headers: corsHeaders }) } const res = NextResponse.next() Object.entries(corsHeaders).forEach(([key, value]) => { res.headers.set(key, value) }) return res } export const config = { matcher: '/api/:path*', }