[英]Hiding URL in fetch request on client-side in Next.js
I have a simple contact form in Next.js that sends an email by using the FormSubmit api when the submit button is clicked: The code for the onSubmit
handler is as follows:我在 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));
};
I want to hide the fetch request URL ie, https://formsubmit.co/ajax/your@email.com
on the client side, which is visible from the DevTools when the fetch request is made.我想在客户端隐藏提取请求 URL 即
https://formsubmit.co/ajax/your@email.com
,在发出提取请求时从 DevTools 中可以看到。 I can't figure out how to do so in Next.js. Is there a way to do it?我不知道如何在 Next.js 中这样做。有办法吗?
While you can't hide the request made from the browser, you can use an API route to mask the URL of the external service.虽然您无法隐藏从浏览器发出的请求,但您可以使用 API 路由来屏蔽外部服务的 URL。
Create an API route (let's say /api/form-submit
) which calls https://formsubmit.co/ajax/your@email.com
, and will act as a proxy.创建一个 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}`)
}
}
Then from the client-side, make a request against the newly created API route instead.然后从客户端向新创建的 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.