我在让后端接受从我用于前端的日期选择器组件返回的值传递的值时遇到问题。我正在使用 react 日历库中的日历。我执行了 console.log() 来查看存储为日期的格式,并使用 Postman 尝试使用该日期发出 POST 请求。我正在尝试添加一个如下所示的对象:
{
"id": 2,
"customer": "Wal Mart",
"destination": "Chicago,IL",
"driver": "Jeff",
"deliveryDate": "Thu Apr 23 2020 01:57:47 GMT-0500 (Central Daylight Time)"
}
我得到的响应指出“JSON解析错误:无法从字符串反序列化java.util.Date
类型的值”Thu Apr 23 2020 01:57:47 GMT-0500(中部夏令时) Time)\"。这就是我的 React 文件中的表单组件的样子
class Add extends Component {
constructor(props){
super(props)
this.state = {
id: '',
customer: '',
destination: '',
driver: '',
deliveryDate: new Date()
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(event){
this.setState({[event.target.name]: event.target.value})
console.log(this.state)
}
onChange = deliveryDate =>
this.setState({ deliveryDate })
submitHandler = e => {
axios.post('http://localhost:8080/add', this.state)
}
render() {
const { customer, destination, driver, deliveryDate} = this.state
return (
<div className="add-form">
<Form onSubmit={this.submitHandler}>
<Form.Group >
<Form.Label>Customer</Form.Label>
<Form.Control type="text" name="customer" value = {customer} onChange= {this.handleChange} />
<Form.Label>Destination</Form.Label>
<Form.Control type="text" name="destination" value= {destination} onChange={this.handleChange} />
<Form.Label>Driver</Form.Label>
<Form.Control type="text" name="driver" value= {driver} onChange={this.handleChange} />
<Form.Label>Delivery Date</Form.Label>
<Calendar name="date" value= {deliveryDate} onChange={this.onChange}/>
</Form.Group>
<Button variant="success" type="submit" className="add-button1" href={"/"}>Add Load</Button>
</Form>
</div>
);
}
}
我可以做些什么来格式化日期,以便我的帖子请求真正通过? 谢谢
最佳答案
您可以尝试将日期时间作为纪元时间发送,然后在后端将其转换为日期对象..
前端就像
submitHandler = e => {
const { deliveryDate } = this.state;
axios.post('http://localhost:8080/add', { ...this.state, deliveryDate: deliveryDate ? deliveryDate.getTime() : null })
}
你的后端就像..
Long deliveryDate = abc.getDeliveryDate();
Date deliveryDateObj = new Date(deliveryDate);
关于java - 无法将 Date 对象从 React 传递到后端到 Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61381391/