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

调用Vercel Serverless Function时客户端出现404错误求助

Vercel Serverless Function 404 问题排查与解决

你遇到的POST请求404问题,主要是Vercel对Serverless函数的识别规则和部署配置问题导致的,以下是具体排查和解决步骤:

1. 修复函数文件命名

Vercel要求api目录下的函数文件必须带明确后缀(.js/.ts),你当前的/api/form没有后缀,Vercel无法识别这是一个Serverless函数文件。

修改方法:将/api/form重命名为/api/form.js。

2. 确认项目目录结构

api文件夹必须放在项目根目录下,不能嵌套在dist或其他子文件夹中。正确的目录结构应该是:

你的项目根目录/
├── api/
│   └── form.js
├── dist/
│   ├── index.html
│   └── index.js
└── package.json

如果你的静态资源输出目录是dist,需要在项目根目录创建vercel.json配置文件,指定静态资源目录:

{
  "buildCommand": "npm run build", // 替换成你的实际构建命令
  "outputDirectory": "dist"
}

3. 正确测试与部署

  • 本地测试必须使用vercel dev命令启动开发服务器,不能直接打开dist目录下的HTML文件(直接打开会把/api/form指向本地文件系统,而非Vercel函数)。
  • 重新部署到Vercel后,登录Vercel控制台查看部署日志,确认Serverless函数form是否被成功检测并部署。

4. 验证请求路径

部署后,检查请求路径是否正确:如果使用Vercel默认域名(比如xxx.vercel.app),请求URL应为https://xxx.vercel.app/api/form;如果是自定义域名,替换域名即可。客户端代码中的相对路径/api/form在部署后会自动拼接域名,无需修改。


修改后的代码示例

客户端代码(/dist/index.js)

async function handleForm() {
  let name = encodeInput(document.getElementById("floating_name").value);
  let email = encodeInput(document.getElementById("floating_email").value);
  let budget = encodeInput(document.getElementById("floating_budget").value);
  let description = encodeInput(document.getElementById("floating_description").value);

  try {
    const formData = { name, email, budget, description };
    console.log("formData", formData)
    const response = await fetch("/api/form", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    const data = await response.text();
    console.log("data", data);

  } catch (error) {
    console.error('Error:', error);
  }
}

Serverless函数代码(/api/form.js)

module.exports = async (req, res) => {
  try {
    const formData = req.body;
    console.log("Received form data:", formData);

    res.status(200).json({ success: true });
  } catch (error) {
    console.error('Error processing the request:', error.message);
    res.status(500).json({ error: 'Internal Server Error' });
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:09:58