[英]React.js - When authorizing on the site, if the data is incorrect, how can I get a response with a text error?
我使用电子邮件和密码将数据发送到API。 具有库devise-token-auth的API Ruby on Rails
signinform.js
.................................................. ....
onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
() => {console.log('ok!')},
({resp}) => { console.log(resp.errors); }
);
} ................................................................ ........
动作/ signInActions.js
import axios from 'axios';
export function userSignInRequest(userData){
return dispatch => {
return axios.post('/auth/sign_in', userData);
}
}
如果电子邮件或密码不正确,我会回复:
{"errors":["Invalid login credentials. Please try again."]}
但是console.log(resp.errors); 显示未定义。 如果我把(resp) => { console.log(resp); }
(resp) => { console.log(resp); }
我得到的控制台:
错误:请求失败,XMLHttpRequest.handleLoad(xhr.js?ec6c:77)的定居点(settle.js?db52:18)的createError(createError.js?16d0:16)的状态码为401
我如何在console.log(resp)中出现错误;
那是因为你的方式已经写resp
的说法。 您已在{resp}
类的括号中写下了resp。 这意味着无论何时将任何对象传递给该函数, resp
都将等于该对象的resp
属性。 但是由于响应仅具有errors
属性,而没有resp
属性,因此显示为undefined。
因此,您可以执行以下任一操作
onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
() => {console.log('ok!')},
(resp) => { console.log(resp.errors); }
);
要么
onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
() => {console.log('ok!')},
({errors}) => { console.log(errors); }
);
编辑:
this.props.userSignInRequest(this.state).then(() =>{
console.log('ok!')
}).catch((resp) => {
console.log(resp.response.data);
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.