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

axios提交注册请求报Request failed with status code 400如何解决

Axios注册接口400错误排查

问题背景

使用axios对接用户注册接口时,提交表单返回Request failed with status code 400错误,未定位到根因。

现有实现代码

Redux注册Action代码

export const userRegister = (
  firstName,
  lastName,
  phone,
  email,
  password,
  role,
  username
) => {
  return async (dispatch) => {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    }

    try {
      const res = await axios.post(
        `http://localhost:8000/api/v1/register`,
        { firstName, lastName, phone, email, password, role, username },
        config
      )
      console.log(res)
      // localStorage.setItem('token', res.data.token)

      dispatch({
        type: REGISTER_SUCCESS,
         payload: {
           successMessage: res.data.message,
           token: res.data.token,
         },
      })
    } catch (error) {
      console.log(error.response)
      dispatch({
        type: REGISTER_FAIL,
        payload: {
          error: error.response.data,
        },
      })
    }
  }
}

表单提交处理代码

const handleSubmit = async (e) => {
    e.preventDefault()
      dispatch(
        userRegister(
          firstName,
          lastName,
          phone,
          email,
          password,
          role,
          username
        )
  }

捕获到的错误信息

Error: Request failed with status code 400
    at createError (createError.js:16:1)

问题定位&修复

HTTP 400状态码的核心原因是请求内容不符合服务端校验规则,按以下顺序排查即可:

  • 先修复显性语法错误
    你的handleSubmit函数存在括号未闭合的语法问题,会导致参数传递异常,修正后代码如下:
const handleSubmit = async (e) => {
  e.preventDefault()
  dispatch(
    userRegister(
      firstName,
      lastName,
      phone,
      email,
      password,
      role,
      username
    )
  )
}
  • 查看后端返回的具体错误信息
    你当前只打印了axios封装的通用错误,没有拿到服务端返回的校验详情:
    1. 打开浏览器开发者工具,切换到Network面板,重新提交表单找到/api/v1/register请求
    2. 查看该请求的Response标签页内容,会明确标注错误原因:常见原因包括字段名和后端要求不匹配、必填参数为空、参数格式错误(比如手机号/邮箱格式不符合规则、密码长度不足、role字段传了不支持的值)、用户名/邮箱已被占用等
  • 优化错误捕获逻辑
    当前catch块直接读取error.response.data存在兼容问题,遇到网络错误时error.response为undefined会触发二次报错,优化为:
catch (error) {
  const errorContent = error.response?.data || '请求异常,请检查网络连接'
  console.log('注册错误详情:', errorContent)
  dispatch({
    type: REGISTER_FAIL,
    payload: {
      error: errorContent,
    },
  })
}
  • 提交前做前端参数校验
    在调用dispatch之前先对表单字段做非空、格式校验,避免无效请求发到后端。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:24:20