36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
import { NextResponse } from 'next/server'
|
|
|
|
/**
|
|
* CORS 配置
|
|
* 允许 Medusa 开发服务器访问 Payload API
|
|
*/
|
|
const ALLOWED_ORIGINS = [
|
|
'http://localhost:9000', // Medusa 开发服务器
|
|
'http://localhost:8000', // Storefront 默认 端口
|
|
process.env.MEDUSA_URL,
|
|
process.env.ADMIN_URL,
|
|
].filter(Boolean) as string[]
|
|
|
|
/**
|
|
* 添加 CORS 头部到响应
|
|
*/
|
|
export function addCorsHeaders(response: NextResponse, origin?: string | null): NextResponse {
|
|
// 检查 origin 是否在允许列表中
|
|
const allowedOrigin = origin && ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0]
|
|
|
|
response.headers.set('Access-Control-Allow-Origin', allowedOrigin)
|
|
response.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
|
|
response.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
|
|
response.headers.set('Access-Control-Allow-Credentials', 'true')
|
|
|
|
return response
|
|
}
|
|
|
|
/**
|
|
* 处理 OPTIONS 预检请求
|
|
*/
|
|
export function handleCorsOptions(origin?: string | null): NextResponse {
|
|
const response = NextResponse.json({}, { status: 200 })
|
|
return addCorsHeaders(response, origin)
|
|
}
|