CORS 跨域处理
开发环境可配置 CORS 允许跨域请求访问开发服务器。
启用 CORS
JavaScript
export default defineConfig({
server: {
cors: true // 允许所有跨域请求
}
})
CORS 配置选项
JavaScript
export default defineConfig({
server: {
cors: {
origin: ['http://localhost:8080', 'https://example.com'],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 600
}
}
})
配置选项说明
| 选项 | 说明 | |
|---|---|---|
| origin | 允许的来源 | |
| methods | 允许的方法 | |
| allowedHeaders | 允许的请求头 | |
| credentials | 允许携带凭证 | |
| maxAge | 预检缓存时间 |
注意:cors: true 等同于允许所有来源。
禁用 CORS
JavaScript
export default defineConfig({
server: {
cors: false // 禁用跨域
}
})
CORS 使用场景
| 场景 | 配置 | |
|---|---|---|
| 本地开发调试 | cors: true | |
| 多域名访问 | 指定 origin 数组 | |
| 需携带 Cookie | credentials: true |
CORS 与 Proxy 区别
| 方式 | 场景 | 特点 |
|---|---|---|
| CORS | 外部访问 Vite Server | 服务器端允许 |
| Proxy | Vite Server 访问外部 API | 代理转发请求 |
预检请求处理
浏览器跨域请求会先发送 OPTIONS 预检:
JavaScript
export default defineConfig({
server: {
cors: {
origin: '*',
methods: ['GET', 'POST'],
maxAge: 86400 // 预检缓存一天
}
}
})
要点总结
- cors: true 允许所有跨域
- cors 配置对象精细控制
- origin 指定允许来源
- credentials 允许携带凭证
📝 发现内容有误?点击此处直接编辑