You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vercel应用无法接收Render托管API的JSON数据问题排查

Vercel前端无法接收Render后端API返回JSON的问题

问题情况

在Vercel部署的前端应用,调用Render托管的后端API时无法接收JSON数据。本地环境下Google登录成功后,调用user-details接口能正常获取用户数据,但部署到Vercel后该请求一直处于pending状态。

后端CORS配置

const allowedOrigins = ['http://localhost:3000', 'https://(myvercelapplink).app'];
app.options('*', cors());
app.use(cors({
    origin: function(origin, callback){
      // 允许无origin的请求(比如移动端或curl请求)
      if(!origin) return callback(null, true);
      if(allowedOrigins.indexOf(origin) === -1){
        var msg = 'The CORS policy for this site does not allow access from the specified Origin.';
        return callback(new Error(msg), false);
      }
      return callback(null, true);
    },
    credentials: true
}));

前端Vercel路由重写配置(vercel.json)

{
  "rewrites":  [
    {"source": "/(.*)",
    "destination": "https://(mybackendlink).com"
  }
  ]
}

排查解决方向

  • 修正Vercel重写规则
    当前规则会把前端所有请求(包括静态资源、页面路由)都转发到后端,导致前端自身资源无法正常加载,引发请求pending。应该只转发API路径的请求,示例配置:

    {
      "rewrites": [
        {"source": "/api/(.*)", "destination": "https://(mybackendlink).com/api/$1"},
        {"source": "/(.*)", "destination": "/$1"}
      ]
    }
    

    这样只有/api开头的请求会转发到后端,前端自身的路由和静态资源请求正常处理。

  • 确认CORS的Origin匹配
    检查Vercel应用的实际域名是否和allowedOrigins里的地址完全一致,比如是否多了www前缀、拼写错误等。可以在后端添加日志打印请求的origin头,确认实际请求来源是否在允许列表中:

    app.use(cors({
      origin: function(origin, callback){
        console.log("请求来源Origin:", origin); // 添加日志查看实际来源
        // 原有逻辑保持不变
      },
      credentials: true
    }));
    
  • 确保请求Credentials配置一致
    前端请求时要设置对应参数:用axios的话加withCredentials: true,用fetch的话加credentials: 'include',和后端credentials: true的配置匹配,否则Cookie等凭证无法传递,可能导致请求异常。

  • 检查Render后端状态
    直接在浏览器访问后端的user-details接口,确认后端服务能正常返回数据;查看Render后端的日志,确认是否收到了Vercel前端的请求,有没有报错信息。

内容的提问来源于stack exchange,提问作者s h a u n

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:58:31