最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

在不停止应用程序的情况下拦截400错误请求

IT培训 admin 4浏览 0评论

在不停止应用程序的情况下拦截400错误请求

我一直在尝试在React中创建一个Login表单。通过这种形式,我向api提交了发布请求,然后api相应地发送了响应。但是,在api中,无效的表单会返回400状态,这会将错误记录到控制台,使我无法处理无效的表单。在我的代码中,我试图使用catch方法拦截此错误,以便我可以进行必要的处理。

以下是相关代码:

class LoginModal extends Component {

  state = {
    email: "",
    password: ""
  }

  handleEmailChange = async event => {
    await this.setState({ email: event.target.value, });
  }
  handlePasswordChange = async event => {
    await this.setState({ password: event.target.value, });
  }

  redirect = path => {
    this.props.history.push(path);
  }

  handleSubmit = event => {
    event.preventDefault();

    const user = {
      email: this.state.email,
      password: this.state.password
    };

    api.post(`${api.url}/users/authenticate`, user)
      .then(res => {
          console.log("Succesful login.");
          this.redirect("/dashboard");
      })
      .catch(err => {
          console.log(err);
      })

  }

  render() {
    return (
      //*Render Code*
    );
  }
}

感谢您提供任何帮助。

回答如下:

我认为您将console.log(err)的输出误解为破坏应用程序的异常。尝试记录err.response而不是err,并检查是否可以使用该数据验证请求。

在不停止应用程序的情况下拦截400错误请求

我一直在尝试在React中创建一个Login表单。通过这种形式,我向api提交了发布请求,然后api相应地发送了响应。但是,在api中,无效的表单会返回400状态,这会将错误记录到控制台,使我无法处理无效的表单。在我的代码中,我试图使用catch方法拦截此错误,以便我可以进行必要的处理。

以下是相关代码:

class LoginModal extends Component {

  state = {
    email: "",
    password: ""
  }

  handleEmailChange = async event => {
    await this.setState({ email: event.target.value, });
  }
  handlePasswordChange = async event => {
    await this.setState({ password: event.target.value, });
  }

  redirect = path => {
    this.props.history.push(path);
  }

  handleSubmit = event => {
    event.preventDefault();

    const user = {
      email: this.state.email,
      password: this.state.password
    };

    api.post(`${api.url}/users/authenticate`, user)
      .then(res => {
          console.log("Succesful login.");
          this.redirect("/dashboard");
      })
      .catch(err => {
          console.log(err);
      })

  }

  render() {
    return (
      //*Render Code*
    );
  }
}

感谢您提供任何帮助。

回答如下:

我认为您将console.log(err)的输出误解为破坏应用程序的异常。尝试记录err.response而不是err,并检查是否可以使用该数据验证请求。

发布评论

评论列表 (0)

  1. 暂无评论