在 SignupComponent 中,我发送 POST 请求以注册用户。但是在控制台上我收到错误:在 createError 时请求失败,状态码为 400。尽管每次将新用户添加到我的数据库时。我检查了 MONGODB 指南针和我发送的每个请求,用户都保存在那里。我不知道这里有什么问题。请帮助我是 React Js 的新手。
import React, {Component} from 'react';
import { Button,Form,FormGroup,Input,Label} from 'reactstrap';
import { Redirect } from 'react-router-dom';
import axios from 'axios';
class SignupComponent extends Component{
constructor(){
super();
this.state = {
input: {},
errors: {}
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
let input = this.state.input;
input[event.target.name] = event.target.value;
this.setState({
input:input
});
}
handleSubmit(event) {
event.preventDefault();
if(this.validate()){
console.log(this.state);
axios.post("http://localhost:3000/register", {
params:{
data:this.state.input
}
}).then((res)=>{
let input = {};
input["username"] = "";
input["password"] = "";
this.setState({input:input});
alert('User Added');
this.props.toggleSignupModal();
<Redirect to='/' />
}).catch((err)=>{
console.log(err);
})
}
}
validate(){
let input = this.state.input;
let errors = {};
let isValid = true;
if (!input["username"]) {
isValid = false;
errors["username"] = "Cannot be empty";
}
if (!input["password"]) {
isValid = false;
errors["password"] = "Cannot be empty";
}
this.setState({
errors: errors
});
return isValid;
}
render(){
return(
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label htmlFor="username">Username</Label>
<Input type="text" id="username" name="username"
value={this.state.input.topic}
onChange={this.handleChange}
/>
<div className="text-danger">{this.state.errors.topic}</div>
</FormGroup>
<FormGroup>
<Label htmlFor="password">Password</Label>
<Input type="password" id="password" name="password"
value={this.state.input.content}
onChange={this.handleChange}
/>
<div className="text-danger">{this.state.errors.content}</div>
</FormGroup>
<Button type="submit" value="submit" color="primary">Submit</Button>
</Form>
)
}
}
export default SignupComponent;
以下是我保存新用户的后端代码。
app.post("/register",(req,res)=>{
User.register(new User({username:
req.body.params.data.username}),req.body.params.data.password,function(err,user){
if(err){
console.log(err);
}
passport.authenticate("local")(req,res,function(){
console.log(user);
})
})
});
我不知道是护照有问题还是什么。请帮忙。