如何修改config设置允许跨域访问?CORS配置实战指南
问题原因
- 浏览器安全限制
- 未返回
Access-Control-Allow-Origin
头 - 复杂请求未预检(OPTIONS请求失败)
- 未返回
- 服务器配置遗漏
- Nginx/Apache未启用CORS模块
- 未处理带凭证的请求(
credentials: true
)
解决方法
环境 | 配置代码示例 |
---|---|
Nginx | add_header 'Access-Control-Allow-Origin' '*';<br>add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS'; |
Apache | Header set Access-Control-Allow-Origin "*"<br>Header set Access-Control-Allow-Headers "Content-Type" |
Node.js | app.use(cors({ origin: ['https://yoursite.com'] })) |
更新时间:2025-07-22 16:44:57