获取 Vercel 无服务器函数时出现客户端 404 错误

问题描述 投票:0回答:1

我用 html、tailwindcss 和 vanilla javascript 创建了一个静态网站。我正在尝试在客户端向 Vercel 的无服务器功能创建一个简单的 POST 请求。我在 Vercel 上部署了这个。

每次触发客户端 API 时,我都会收到 404 未找到错误。它永远不会进入无服务器端。我按照 Vercel 文档将无服务器函数放置在 api 文件夹中。

客户端 /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);
  }

我的无服务器功能 /api/表单

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);

    // Set an error status code and send an error response
    res.status(500).json({ error: 'Internal Server Error' });
  }
};
javascript html rest tailwind-css vercel
1个回答
0
投票

问题似乎可能与您在客户端的获取函数中使用的路径有关。部署到 Vercel 时,api 文件夹内的无服务器函数会自动映射到 /api 路径。

因此,在客户端代码中,您应该调整获取 URL 以匹配无服务器函数的正确路径。更新这部分客户端代码:

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

至:

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

Ensure that the path /api/form matches the structure you have in your project. If you are still encountering issues, you might want to check the network tab in your browser's developer tools to see the exact request being made and the response received. This can provide additional insights into what might be going wrong.

© www.soinside.com 2019 - 2024. All rights reserved.