我正在尝试使用React前端中的以下函数将axios的POST请求发送到Rails API:
export function registerUser({ name, email, password }) {
var postdata = JSON.stringify({
auth: {
name, email, password
}
});
return function(dispatch) {
axios.post(`${API_URL}/user_token`, postdata )
.then(response => {
cookie.save('token', response.data.token, { path: '/' });
dispatch({ type: AUTH_USER });
window.location.href = CLIENT_ROOT_URL + '/dashboard';
})
.catch((error) => {
errorHandler(dispatch, error.response, AUTH_ERROR)
});
}
}
Knock gem期望以下格式的请求:
{"auth": {"email": "foo@bar.com", "password": "secret"}}
我当前的函数似乎生成正确的格式(在浏览器devtools中检查请求),但我收到以下错误:
未捕获(承诺)错误:对象作为React子对象无效(找到:具有键{data,status,statusText,headers,config,request}的对象) . 如果您要渲染子集合,请使用数组,或使用React附加组件中的createFragment(object)包装对象 . 检查Register的render方法 .
class Register extends Component {
handleFormSubmit(formProps) {
this.props.registerUser(formProps);
}
renderAlert() {
if(this.props.errorMessage) {
return (
<div>
<span><strong>Error!</strong> {this.props.errorMessage}</span>
</div>
);
}
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
{this.renderAlert()}
<div className="row">
<div className="col-md-6">
<label>Name</label>
<Field name="name" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Email</label>
<Field name="email" className="form-control" component={renderField} type="text" />
</div>
</div>
<div className="row">
<div className="col-md-12">
<label>Password</label>
<Field name="password" className="form-control" component={renderField} type="password" />
</div>
</div>
<button type="submit" className="btn btn-primary">Register</button>
</form>
);
}
}
1 回答
该错误是由代码中的以下行引起的
提出的例外明确解释了这一点 . 而不是设置
error.response
,尝试使用error.response中的实际数据 . 例如error.response.data
. 此外,您可以尝试用字符串替换error.response
并查看其行为,然后从error.response.data
引用您需要的字符串 .