【问题标题】:Convert from Ajax to Axios从 Ajax 转换为 Axios
【发布时间】:2019-07-17 15:24:35
【问题描述】:

我创建了一个使用 JQuery 完成的网站,但我现在正在尝试学习反应,但不确定如何使用 axios 连接我的后端 API。有谁知道这相当于 axios。

    $("#log-form").submit(function (event) {
        event.preventDefault();
        $.ajax({
            type: 'POST',
            url: '/users/login',
            dataType: 'json',
            data: {
                'user_name': event.target.inputUsername.value,
                'password': event.target.inputPassword.value
            },
            success: function(token){
                 $(location).attr('href', '/feed' ); // Redirect to logged in page
            },
            error: function(errMsg) {
                swal(
                    'Oops...',
                    errMsg.responseJSON.body,
                    'error'
                )
            }
        });
    });

【问题讨论】:

标签: jquery ajax reactjs axios


【解决方案1】:

基本上,您需要设置一个React controlled form

Axios 使用promises,因此您可以在try/catch 块内使用async/await,或者使用更传统的.then/.catch

注意:始终catch 你的承诺。初级开发人员的一个常见错误是假设服务器永远不会抛出错误。因此,它可能会导致整个应用程序崩溃。

设置好受控表单后,您将使用 API 调用创建自定义 handleSubmit 类方法回调:

constructor() {
  super();

  this.state = { 
    error: "", 
    password: "",
    username: ""
  }

  this.handleSubmit = this.handleSubmit.bind(this);
}

handleSubmit(e) {
  e.preventDefault(); // in this case, e.preventDefault() prevents the page from refreshing
  const { username, password } = this.state; // grabs current input values from React state

  axios.post('/users/login', { user_name: username, password: password }) // sends a POST request to "/users/login" with data
  .then(token => { // if the POST request was successful...
     // do whatever you need to do with the token (set it to localStorage or Redux state)
     this.props.history.push("/feed");  // then you'll redirect -- this assumes you're at the parent component AND using react-router-dom
   })
  .catch(err => this.setState({ error: err.toString() })); // if there's an error, you'll set it to state and display it in the render method below  
}

render() {
  return (
    <div>
      <form onSubmit={this.handleSubmit}>
      ...etc
      <form>
      {this.state.error && 
         <p>
           This was a problem logging in: {this.state.err}
         </p>
      }
    </div>
  )
}

【讨论】:

    【解决方案2】:

    改成axios..

           axios.post ('users/login', { 
            User_name: event.taget.whatever,
            Password: event.taget.whatever
            })
          .then (response => {
             //whatever you want to do with data you recieved
            }; 
    

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 2021-11-14
      • 2016-09-02
      • 1970-01-01
      • 2021-11-12
      • 2019-06-24
      • 1970-01-01
      • 2019-07-11
      • 2019-12-18
      相关资源
      最近更新 更多