NodeJS 表单操作未将我引导至相应页面

s8vozzvw  于 2023-06-05  发布在  Node.js
关注(0)|答案(1)|浏览(129)

我有以下表格:

<form action="/payment" onSubmit={onSubmitForm}>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                <input />
</form

 <button className="w-full bg-purple-500 py-3 text-center text-white">
                    Register Now
                  </button>

当我点击提交按钮时,我没有被定向到付款路径。这就是我在onSubmitForm函数中的内容

async function onSubmitForm(e){
    e.preventDefault();
    try {

      const response = await fetch("http://localhost:5000/user", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(data)
      } )
      
      console.log("res: ", response.body)
    } catch (error) {
      console.log("EROR: ", error.message)
    }
  }

我知道还有其他方法可以改变路径,但我想弄清楚为什么这个动作在这个上下文中不起作用。

wlzqhblo

wlzqhblo1#

以下是可能适合您的设置:

export default function App() {
  async function onSubmitForm(e) {
    e.preventDefault();
    try {
      const response = await fetch("http://localhost:5000/user", {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify("data")
      });

      console.log("res: ", response.body);
      window.location.replace("/payment");
      // You might also want to check `location.assign`
      // https://developer.mozilla.org/en-US/docs/Web/API/Location/assign 
    } catch (error) {
      console.log("EROR: ", error.message);
    }
  }

  return (
    {/* No need for action, as the onSubmitForm fetch is taking care of POST-ing the data */}
    <form onSubmit={onSubmitForm}>
      <input />
      <button>Register Now</button>
    </form>
  );
}

根据应用程序的设置,您可能需要考虑使用React Router等路由库,并使用useNavigateredirect将应用程序重定向到另一个动态路由。

相关问题