簡體   English   中英

在 Next.js 的客戶端獲取請求中隱藏 URL

[英]Hiding URL in fetch request on client-side in Next.js

我在 Next.js 中有一個簡單的聯系表單,當單擊提交按鈕時,它通過使用FormSubmit api 發送一個 email: 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 中這樣做。有辦法嗎?

雖然您無法隱藏從瀏覽器發出的請求,但您可以使用 API 路由來屏蔽外部服務的 URL。

創建一個 API 路由(比如說/api/form-submit ),它調用https://formsubmit.co/ajax/your@email.com ,並將充當代理。

// /pages/api/form-submit
export default 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));
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM