gpt4 book ai didi

javascript - 快速发送 json 但客户端接收未定义

转载 作者:行者123 更新时间:2023-12-03 03:52:55 26 4
gpt4 key购买 nike

我遇到了一个非常令人沮丧的问题。 Express 服务器上的简单 json 常量作为 json 对象发送,但是当接收该对象并尝试在客户端上从中提取错误时,来自服务器的 json 对象显示为 undefined 对于我的一生,我无法弄清楚为什么。

似乎将 res.status(400).json(errors); 从服务器更改为 res.json(errors); 并从中提取错误数据isValid is true 的客户端代码块,我能够获取错误消息 - 因此,发送 400 状态可能与此有关。

还有其他人遇到过这个问题吗?我很感激任何关于如何解决的建议。

Express - api.js

 if( isValid ) {
res.json({success: true});
} else {
const errors = { username: 'This field is required',
email: 'Email is invalid' };

res.status(400).json(errors);
}

注册表单组件

    this.setState({errors: {}, isLoading: true});
this.props.userSignupRequest(this.state).then(
() => {
this.props.history.push('/');
},
({data}) => {
console.log(data); //undefined
this.setState({errors: data, isLoading: false})
}
)

SignupAction.js

import axios from 'axios';

export function userSignupRequest(userData) {
return dispatch => {
return axios.post('http://myhost/api/signup', userData);
}
}

最佳答案

根据 Axios manual :

When using catch, or passing a rejection callback as second parameter of then, the response will be available through the error object as explained in the Handling Errors section.

所以:

this.props.userSignupRequest(this.state).then(
() => {
this.props.history.push('/');
},
error => {
const {data} = error.response;
console.log(data);
this.setState({errors: data, isLoading: false});
}
)

关于javascript - 快速发送 json 但客户端接收未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45086081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com