首页 > 解决方案 > 在 reactjs 中使用 axios 发出请求时出现 400(错误请求)状态码

问题描述

错误当尝试在 reactjs 中使用 axios 时,它正在向邮递员发出请求,它显示 400 状态代码

我已经尝试过 - 添加删除标题 - 添加边界:--foo

handleSubmit(event) {
let data = new FormData();
      data.append("username", this.state.username)
      data.append("password", this.state.password)
      data.append("confirm_password", this.state.confirm_password)
      data.append("email", this.state.email)
      event.preventDefault();
      axios({
         method: 'post',
         url: 'http://localhost:8000/api/account/register/',
         data: data,
      headers:{
         "Content-Type":"application/x-www-form-urlencoded; boundary:XXboundaryXX"
      }
      })
         .then((response) => {
             console.log('bitchhh');

         })
         .catch((response) => {
            //handle error
            console.log(response);
         });
   }

铬合金[ 错误代码[![邮递员] 3

标签: djangoreactjsapidjango-rest-framework

解决方案


如果数据有任何错误,rest framework 不会返回 2xx 状态码,它总是返回 400 bad request。这意味着您发送的请求中有错误。

邮递员也收到 400 错误请求,但它显示响应数据(错误消息)。

axios 将 400 状态代码视为错误,因此您必须在 catch 块中处理它。如果您想访问发送错误的响应,您可以从

.catch((err) => {
    //handle error
    console.log(err.response.data);
 });

推荐阅读