【发布时间】:2018-04-12 11:55:03
【问题描述】:
我正在尝试传递一个名为 Questions 的对象,该对象具有 3 个属性。第一个和第三个属性是字符串类型,第二个是布尔类型。例如:{"description: "What is ecommerce" , "requireMeeting": true, "expID": "1234"}
当我尝试通过前端发送发布请求时,我收到以下错误。 (但是,当我通过环回资源管理器添加新对象时,它工作正常)
Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)
这是向数据库发送新对象的 addQues 函数
addQues(newQues) {
console.log(newQues);
axios.request({
method: 'Post',
url: 'http://localhost:3001/api/Questions',
data: newQues
}).then(response => {
}).catch(err => console.log(err));
}
这是onSubmit函数的代码,它将要添加的对象传递给addQues
onSubmit(e) {
const newQues = {
description: this.state.description,
requireMeeting: this.state.requireMeeting,
expID: this.state.expID
};
this.addQues(newQues);
e.preventDefault();
}
这是完整的代码
import React, { Component } from 'react';
import axios from 'axios';
import '../Styles.scss';
class Questions extends Component {
addQues(newQues) {
console.log(newQues);
axios.request({
method: 'Post',
url: 'http://localhost:3001/api/Questions',
data: newQues
}).then(response => {
}).catch(err => console.log(err));
}
constructor() {
super();
// this.onChange = this.onChange.bind(this);
this.onDescriptionChange = this.onDescriptionChange.bind(this);
this.onExpIdChange = this.onExpIdChange.bind(this);
this.onIsmeetingChange = this.onIsmeetingChange.bind(this);
this.state = {
description: '',
requireMeeting: false,
expID: ''
};
}
onExpIdChange(e) {
this.setState({
expID: e.target.value
});
}
onDescriptionChange(e) {
this.setState({
description: e.target.value
});
}
onIsmeetingChange(e) {
this.setState({
requireMeeting: true
// document.getElementById("checkbox").checked = true;
});
}
onSubmit(e) {
const newQues = {
description: this.state.description,
requireMeeting: this.state.requireMeeting,
expID: this.state.expID
};
this.addQues(newQues);
e.preventDefault();
}
render() {
return (
<div>
<br/>
<h1> DO NOT HESISTATE TO ASK OUR EXPERTS </h1>
<form onSubmit={this.onSubmit.bind(this)}>
<div className="input-field">
<label htmlFor="description"> Description </label>
<textarea rows="10" cols="100" name="description" onChange={this.onDescriptionChange} />
</div>
<div className="input-field">
<input type="text" name="expID" onChange={this.onExpIdChange} />
<label htmlFor="name"> expID </label>
</div>
<div className="checkbox">
<label>
<input type="checkbox" name="requireMeeting"
onClick={this.onIsmeetingChange} />Meeting
</label>
</div>
<input type ="submit" value="ASK" className="btn" />
</form>
</div>
);
}
}
export default Questions;
【问题讨论】:
-
您说的是“put”请求,但您的代码显示“post”——您的意思是 post,对吧?
-
哦,是的,发帖@RaymondCamden
-
如果您查看您的浏览器开发工具,您能否确认问题数据在表单帖子的正文中正确传递?
-
你可以试试
data: JSON.stringify(newQues)
标签: reactjs http post loopbackjs