我有用户登录名,并且我有2个错误处理程序
>电子邮件和密码为空
>电子邮件和密码与数据库不匹配
通过邮递员我发送
>空的用户名和密码结果是
{
"errors": {
"email": "please enter valid emails",
"password": "please enter password"
}
}
>电子邮件和密码错误,结果是
{
"general": "email or password not match"
}
我注意到第一个错误有对象错误,第二个没有
我的反应js代码是
// i remove css and imports
class login extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
loading: false,
errors: {}
}
}
handleChnage = (event) => {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit = (event) => {
// console.log('hi');
event.preventDefault();
this.setState({
loading: true
});
const userData = {
email: this.state.email,
password: this.state.password
}
axios.post('/login', userData)
.then((res) => {
//console.log(res.data)
this.setState({
loading: false
});
this.props.history.push('/');
})
.catch((err) => {
console.log(err.response.data)
// let errors ={email:'',password:''}
this.setState({
//errors11: err.response.data.errors,
errors : err.response.data.errors,
// error2:err.response.data,
loading: false
})
})
}
render() {
const { classes } = this.props;
const { errors, loading,} = this.state;
return (
<Grid container className={classes.form}>
<Grid item sm />
<Grid item sm >
<img src={AppIcon} alt="app cion" className={classes.image} />
<Typography variant="h2" className={classes.pagetitle}>Login</Typography>
<form noValidate onSubmit={this.handleSubmit}>
<TextField id="email" name="email" type="email" label="Email" className={classes.textfeild}
helperText={errors.email} error={errors.email ? true : false} value={this.state.email} onChange={this.handleChnage} fullWidth />
<TextField id="password" name="password" type="password" label="Password" className={classes.textfeild}
helperText={errors.password} error={errors.password ? true : false} value={this.state.password} onChange={this.handleChnage} fullWidth />
{errors.general &&(
<Typography variant="body2" className={classes.customerror}>
{errors.general}
</Typography>
)}
<Button type="submit" variant="contained" color="primary" className={classes.button}>Login </Button>
</form>
</Grid>
<Grid item sm />
</Grid>
)
}
}
login.propTypes = {
classes: PropTypes.object.isRequired
}
export default withStyles(styles)(login);
如果我发送电子邮件和密码错误,我的问题是在此代码中
93 | helperText = {errors.email} error = {errors.email吗? true:false} value = {this.state.email} onChange = {this.handleChnage} fullWidth
这行我有错误,这是我的控制台日志
general: "email or password not match"
我该如何处理此类错误?
解决方法:
查看您的请求处理代码和响应,我可以看到错误响应在处理错误方面是不一致的.我认为您应该考虑将响应固定为一致的.我会尝试在提交的错误处理中替换行
errors : err.response.data.errors,
会为一般错误创造结构的东西:f.e.
errors : {...err.response.data.errors, general: err.response.data.general}