我遇到一个有趣的错误(当使用POST http://127.0.0.1:8000/api/auth/signup 422 (Unprocessable Entity)
进行POST请求以将用户信息存储到我的数据库时,axios
。
我已经使用Laravel(PHP框架)创建了一个端点,并通过带有正确标题的Postman进行了测试,并且工作正常,但是由于某些原因,它的前端部分让我感到困惑,并且不确定我该怎么做。壁。我究竟做错了什么?如何将用户信息成功存储到数据库中?
import React, {Component} from 'react';
import axios from "axios";
class Register extends Component {
constructor(props) {
super(props);
this.state = {
username: "",
email: "",
password: ""
};
this.userNameHandler = this.userNameHandler.bind(this);
this.emailHandler = this.emailHandler.bind(this);
this.passwordHandler = this.passwordHandler.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
userNameHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.username);
}
emailHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.email);
}
passwordHandler(e) {
this.setState({
username: e.target.value,
});
console.log(this.state.password);
}
handleSubmit(e) {
e.preventDefault();
const user = {
name: this.state.name,
email: this.state.email,
password: this.state.password
}
JSON.stringify(user);
const headers = {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
}
this.setState({
username: e.target.value
});
axios.post('http://127.0.0.1:8000/api/auth/signup', user, headers)
.then(response => {
console.log(response);
console.log(response.data);
}).catch(error => {
console.log("AXIOS ERROR!! " + error);
});
}
render() {
return (
<div className="container">
<div id="login-row" className="row justify-content-center align-items-center">
<div id="login-column" className="col-md-6">
<div id="login-box" className="col-md-12">
<form id="login-form" className="form" method="post" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="username" className="text-info">Username:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.userNameHandler}/>
</div>
<div className="form-group">
<label htmlFor="username" className="text-info">Email:</label><br/>
<input type="text" name="username" id="username" className="form-control" onChange={this.emailHandler}/>
</div>
<div className="form-group">
<label htmlFor="password" className="text-info">Password:</label><br/>
<input type="text" name="password" id="password" className="form-control" onChange={this.passwordHandler}/>
</div>
<div className="form-group">
<input type="submit" name="submit" className="btn btn-info btn-md"
value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
}
export default Register;
axios.post('http://127.0.0.1:8000/api/auth/signup', user, {headers})
您正在尝试传递标题。但这应该是config对象中的键。