Next.js部署Vercel后CORS配置无效问题求助
问题:Vercel部署Next.js应用后API请求触发CORS错误
错误信息
Access to fetch at 'http://localhost:3000/api/' from origin [...] has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
已配置的CORS规则
next.config.mjs
/** @type {import('next').NextConfig} */ const nextConfig = { async headers() { return [ { // 匹配所有API路由 source: "\/api\/:path*", headers: [ { key: "Access-Control-Allow-Credentials", value: "true" }, { key: "Access-Control-Allow-Origin", value: "*" }, { key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,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" }, ] } ] } }; export default nextConfig;
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,DELETE,PATCH,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" } ] } ] }
已尝试的排查操作
- 将
Access-Control-Allow-Origin值改为"http://localhost:3000",问题未解决 - 使用环境变量
NEXT_PUBLIC_BASE_URL = http://localhost:3000拼接请求URL,CORS错误依然存在
相关请求代码
POST请求
try { const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/`, { method: "POST", headers: { "Content-Type": "application/json", }, cache: "no-store", body: JSON.stringify({ text }), }) console.log('Successfully uploaded confession!: ', text); setSubmitted(!submitted); setText(''); } catch (error) { console.error("Error posting confession from home page:", error); }
GET请求
const getConfessions = async () => { const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/`); const confessions = await res.json(); setConfessions(confessions.reverse()); return confessions; }
内容的提问来源于stack exchange,提问作者letmeeatbrioche
相关产品推荐
相关产品推荐

