You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Axios发送POST请求后表单数据附在URL的问题求助

问题根源

你遇到的这个问题是浏览器表单的默认提交行为导致的:当你点击<button type="submit">时,浏览器会自动触发<form>的默认提交逻辑——它会以GET请求的方式把表单数据拼到URL上,同时刷新/跳转页面。这就导致你的axios POST请求还没完成就被页面跳转中断(所以开发者工具里显示请求状态为canceled),最终浏览器跳转到带参数的路由。

解决方案

这里有几个简单的修复方式,任选其一即可:

方案1:在提交处理函数中阻止默认行为

修改你的handleSubmit函数,接收事件参数并调用preventDefault()来阻止浏览器的默认表单提交行为:

const handleSubmit = (event) => {
  // 阻止浏览器默认的表单提交逻辑
  event.preventDefault();
  
  if(validation()) {
    let data = {
      name: name,
      email: email,
      password: password
    }
    axios.post('/user/create-user', data)
      .then(response => {
        console.log(response)
      })
      .catch(error => {
        console.log(error)
      })
  }
}

同时确保按钮的onClick传递事件:

<button type="submit" onClick={handleSubmit}>Submit</button>

方案2:将按钮类型改为button

把按钮的type从submit改成button,这样点击按钮就不会触发表单的默认提交行为:

<button type="button" onClick={handleSubmit}>Submit</button>

这种方式不需要修改handleSubmit函数,适合简单场景。

方案3:绑定表单的onSubmit事件(更符合语义)

推荐这种方式,因为表单的提交逻辑应该绑定到<form>元素的onSubmit事件上,而不是按钮的onClick:

// 修改handleSubmit函数,同样需要阻止默认行为
const handleSubmit = (event) => {
  event.preventDefault();
  
  if(validation()) {
    let data = {
      name: name,
      email: email,
      password: password
    }
    axios.post('/user/create-user', data)
      .then(response => {
        console.log(response)
      })
      .catch(error => {
        console.log(error)
      })
  }
}

// 表单绑定onSubmit事件
return (
  <div>
    <form onSubmit={handleSubmit}>
      <input type="text" required name="name" value={name} onChange={handleChange}/>
      <input type="email" required name="email" value={email} onChange={handleChange}/>
      <input type="password" required name="password" value={password} onChange={handleChange}/>
      <button type="submit">Submit</button>
    </form>
  </div>
)

这种方式更符合HTML表单的设计语义,同时也能正确阻止默认行为。

验证效果

修改后再测试,你会发现:

  • 浏览器URL不会再出现表单参数
  • axios的POST请求能正常完成(不会显示canceled)
  • 页面不会发生不必要的跳转

内容的提问来源于stack exchange,提问作者ShashankAC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 19:07:27