简体   繁体   English

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

[英]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.

相关问题 在 onclick 函数 next.js 中使用客户端道具 - using client-side props in onclick function next.js Next.js中如何访问客户端window方法 - How to access client-side window method in Next.js Next.js 中的动态路由是呈现在服务器端还是客户端? - Are dynamic routes in Next.js rendered server-side or client-side? Next.js:在 getInitialProps() 中获取数据:服务器端 vs 客户端 - Next.js: fetching data in getInitialProps(): server-side vs client-side 在 Next.js 中执行客户端重新加载和更改 url - Do a client side reload and change url in Next.js Next.JS Static 站点生成和客户端 Apollo 获取 - Next.JS Static site generation and client-side Apollo fetching 客户端 JavaScript 应用 (Next.js) 意外中断,没有任何控制台错误 - The client-side JavaScript app (Next.js) breaks unexpectedly, without any console errors Next.js:如何将仅外部客户端的 React 组件动态导入到开发的服务器端渲染应用程序中? - Next.js: How to dynamically import external client-side only React components into Server-Side-Rendering apps developed? 如何在 Next.Js 中重定向(客户端) - How to redirect in Next.Js (CLIENT SIDE) Next JS:在功能组件中获取仅客户端数据的正确方法 - Next JS: Right way to fetch client-side only data in a Functional Component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM