使用React发出发布请求

时间:2018-08-01 15:23:30

标签: javascript node.js reactjs post axios

在我的React应用程序中,我有一个仅包含用户名和密码的表单(以后我也会添加“确认密码”),当提交带有JSON的请求时,应在其正文中包含电子邮件和密码。 / p>

只有经过几次检查,密码才能被接受,如果通过所有这些条件,密码将被接受。

render() {
    return (
      <form className="demoForm" onSubmit={this.handleUserInput} >
        .
        .
        .
        .
        <button type="submit" className="btn btn-primary" disabled={!this.state.formValid}>Sign U p</button>
      </form>
    );
  }

handleUserInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value}, () => { this.validateField(name, value) });
    axios.post('****', {
      value
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  }

我正在使用如上所述的axios,我的问题是我不知道应该怎么用这个****,我正在使用本地主机。这是一个好方法吗?

1 个答案:

答案 0 :(得分:0)

您应该添加将呼叫发布到的地址。 (即/ api / validate_user)

只是附带说明,请尝试分开操作。

 onChangeHandler(e) {
    e.preventDefault()
    const { value, id} = e.target
    this.setState({
        [id]: value
    })
}

更新状态然后提交

onSubmitHandler(e) {
    var self = this;
    e.preventDefault()
    const { userName, password } = this.state;
    // Do validation of password
    axios.post('/api/validateUser', {
       user: userName,
       password: password
    }).then(e => {
        if(e.success){
            console.log("success")
        }
        else if(e.error) {
            console.log("error logging in")
        }
    })
}
相关问题