⚠️ Alpha内测版本警告:此为早期内部构建版本,尚不完整且可能存在错误,欢迎大家提Issue反馈问题或建议
Skip to content

6.4.3 CORS:跨域请求安全策略

一句话破题

CORS 是浏览器在问服务器:"这个来自别的网站的请求,你允许吗?" 它不是在刁难你,而是在保护用户。

核心价值

理解 CORS 能让你:

  • 知道为什么跨域请求会被阻止
  • 正确配置允许的跨域来源
  • 避免"开发时好好的,上线就报错"

快速上手

最小配置

typescript
// app/api/data/route.ts
export async function GET() {
  return Response.json({ data: 'hello' }, {
    headers: {
      'Access-Control-Allow-Origin': 'https://your-frontend.com',
    }
  })
}

export async function OPTIONS() {
  return new Response(null, {
    headers: {
      'Access-Control-Allow-Origin': 'https://your-frontend.com',
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type',
    }
  })
}

多域名白名单

typescript
const allowedOrigins = [
  'https://app.example.com',
  'https://admin.example.com',
]

export async function GET(request: Request) {
  const origin = request.headers.get('origin')
  const headers: Record<string, string> = {}
  
  if (origin && allowedOrigins.includes(origin)) {
    headers['Access-Control-Allow-Origin'] = origin
  }
  
  return Response.json({ data: 'hello' }, { headers })
}

允许携带凭证

typescript
// 需要发送 Cookie 时
headers: {
  'Access-Control-Allow-Origin': 'https://your-frontend.com', // 不能用 *
  'Access-Control-Allow-Credentials': 'true',
}

// 前端请求
fetch(url, { credentials: 'include' })

避坑指南

新手最容易犯的错

  1. 生产环境使用 Access-Control-Allow-Origin: *
  2. 使用 * 的同时又设置 Allow-Credentials: true
  3. 忘记处理 OPTIONS 预检请求