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

Vue3项目Vercel本地Serverless Functions调用返回文件内容问题

问题:Vue3项目中Vercel Serverless函数本地调用返回文件内容而非JSON响应

我在Vue3项目中尝试通过Vercel添加Serverless函数,计划用Vercel CLI实现本地运行。本地服务可以正常启动,但用Axios调用函数时,控制台输出的是函数文件的完整代码内容,而非预期的JSON响应。

环境版本信息

  • Node v20.10.0
  • NPM 10.2.3
  • Vercel CLI 32.7.2
  • Vue 3.2.0
  • Axios: 1.6.2

相关配置与代码

vercel.json

{
  "version": 2,
  "builds": [
    {
      "src": "*.ts",
      "use": "@vercel/node"
    }
  ],
  "rewrites": [
    {
      "source": "/((?!api).*)",
      "destination": "/"
    }
  ]
}

api/example.ts

import type { VercelRequest, VercelResponse } from "@vercel/node";

export default function handler(request: VercelRequest, response: VercelResponse) {
  const { name = "World" } = request.query;

  response.status(200).json({greeting: `Hello ${name}!`});
}

Axios调用代码

const helloWorld = async (name: string) => {
  const api = axios.create({
    baseURL: "http://localhost:3001/api",
    headers: {
      "Content-Type": "application/json",
    },
  });
  const response = await api.get(`/example?name=${name}`);
  return response.data;
};

console.log(await helloWorld("Jim"));

调用后返回的是api/example.ts文件的完整代码文本,而非预期的{"greeting": "Hello Jim!"}。我已查阅资料、尝试多种函数导出方式、查看相关Issue,但均未解决问题。目前看到的示例多与NextJS SSR相关,我确信自己可能犯了低级错误,但无法定位。


问题定位与解决步骤

1. 修正vercel.json的函数匹配规则

当前builds中的src: "*.ts"仅匹配项目根目录下的ts文件,而你的函数位于api/目录下,需调整匹配路径:

{
  "version": 2,
  "builds": [
    {
      "src": "api/*.ts",
      "use": "@vercel/node"
    }
  ],
  "rewrites": [
    {
      "source": "/api/(.*)",
      "destination": "/api/$1"
    },
    {
      "source": "/((?!api).*)",
      "destination": "/"
    }
  ]
}

这里将src改为api/*.ts确保Vercel识别api目录下的函数,同时补充api路径的重写规则,保证请求正确路由到函数处理逻辑。

2. 使用正确的本地启动命令

必须用Vercel CLI的vercel dev启动服务,而非Vue原生的npm run dev。只有vercel dev会加载Serverless函数配置,将/api路径的请求转发到对应的函数。如果需要指定端口3001,执行:

vercel dev --port 3001

3. 验证函数加载状态

启动vercel dev后,终端应输出类似日志,说明函数已被正确识别:

> Ready! Available at http://localhost:3001
> Functions:
>   api/example.ts: http://localhost:3001/api/example

如果没有这行日志,检查vercel.json的路径配置和函数文件位置是否匹配。

4. 确认函数导出格式

保持当前的export default function handler(...)格式,这是Vercel Node函数的标准要求,不要修改为其他导出方式。

内容的提问来源于stack exchange,提问作者THammons

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 23:18:37