在Next.js中隐藏客户端获取请求中的URL

gj3fmq9x  于 2023-03-29  发布在  其他
关注(0)|答案(1)|浏览(209)

我在Next.js中有一个简单的联系表单,当单击提交按钮时,它使用FormSubmit API发送电子邮件:onSubmit处理程序的代码如下:

const handleSubmit = async (e) => {
  e.preventDefault();
  const res = await fetch("https://formsubmit.co/ajax/your@email.com", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
    },
    body: JSON.stringify({
      name: "FormSubmit",
      message: "I'm from Devro LABS",
    }),
  })
    .then((response) => response.json())
    .then((data) => console.log(data))
    .catch((error) => console.log(error));
};

我想在客户端隐藏提取请求URL,即https://formsubmit.co/ajax/your@email.com,当提取请求发出时,它可以从DevTools中看到。我不知道如何在Next.js中做到这一点。有没有办法做到这一点?

ozxc1zmp

ozxc1zmp1#

虽然您无法隐藏从浏览器发出的请求,但可以使用API路由来屏蔽外部服务的URL。
创建一个调用https://formsubmit.co/ajax/your@email.com的API路由(假设为/api/form-submit),并将充当代理。

// /pages/api/form-submit
export default async function handler(req, res) {
    if (req.method !== "POST") {
        res.setHeader('Allow', ["POST"])
        return res.status(405).end(`Method ${req.method} Not Allowed`)
    }

    try {
        const res = await fetch("https://formsubmit.co/ajax/your@email.com", {
            method: "POST",
            headers: req.headers, // Headers passed from the client-side
            body: req.body // Body passed from the client-side
        })
        const data = await res.json()
        res.status(200).json(data)
    } catch(e) {
        res.status(500).end(`An error occurred: ${e}`)
    }
}

然后从客户端,对新创建的API路由发出请求。

const handleSubmit = async (e) => {
    e.preventDefault();
    await fetch("/api/form-submit", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Accept: "application/json"
            },
            body: JSON.stringify({
                name: "FormSubmit",
                message: "I'm from Devro LABS"
            })
        })
        .then((response) => response.json())
        .then((data) => console.log(data))
        .catch((error) => console.log(error));
};

相关问题