Vercel上Node无服务器函数CORS配置问题求助
Vercel Node无服务器函数CORS问题解决方案
方法一:在API函数中直接处理CORS(推荐)
浏览器发起跨域请求时会先发OPTIONS预检请求,仅靠vercel.json的配置可能无法覆盖这种场景,直接在函数中设置响应头并处理OPTIONS请求更可靠:
修改api/index.ts代码:
import type { VercelRequest, VercelResponse } from '@vercel/node'; export default (req: VercelRequest, res: VercelResponse) => { // 配置CORS响应头 res.setHeader('Access-Control-Allow-Credentials', 'true'); res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET,OPTIONS,PATCH,DELETE,POST,PUT'); res.setHeader('Access-Control-Allow-Headers', 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version'); // 处理OPTIONS预检请求,直接返回200结束响应 if (req.method === 'OPTIONS') { return res.status(200).end(); } // 处理业务逻辑 return res.status(200).json({ hello: 'world' }); };
注意:如果请求需要携带凭证(如Cookie),
Access-Control-Allow-Origin不能设为*,需指定具体源(如http://localhost:5173),同时前端fetch要添加credentials: 'include'选项。
方法二:修正vercel.json配置
如果坚持用配置文件管理响应头,需确保路径规则覆盖你的API路径,修改后重新部署项目:
更新vercel.json:
{ "headers": [ { "source": "/api", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" } ] }, { "source": "/api/(.*)", "headers": [ { "key": "Access-Control-Allow-Credentials", "value": "true" }, { "key": "Access-Control-Allow-Origin", "value": "*" }, { "key": "Access-Control-Allow-Methods", "value": "GET,OPTIONS,PATCH,DELETE,POST,PUT" }, { "key": "Access-Control-Allow-Headers", "value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" } ] } ] }
常见排查点
- 部署后在Vercel控制台的项目设置中,确认Headers配置已被正确读取。
- 若启用了凭证支持,前端请求必须搭配
credentials: 'include',且Access-Control-Allow-Origin不能用*。 - 避免同时设置
Access-Control-Allow-Origin: *和Access-Control-Allow-Credentials: true,这会触发浏览器报错。
内容的提问来源于stack exchange,提问作者Nullish
相关产品推荐
相关产品推荐

