【发布时间】:2021-08-26 02:08:03
【问题描述】:
不知道为什么,但是 POST 请求返回 400。邮递员说我的 django 后端运行良好。这一切都发生在 post_flashcards 方法中,任何帮助都会很棒,我愿意根据要求显示任何其他代码。虽然应该没有必要,因为这个组件主要是独立运行的。
class CreateFlashCard extends Component {
constructor(props) {
super(props);
this.state = {
title: '',
collection_id: '',
term: '',
definition: '',
}
this.handleSubmit = this.handleSubmit.bind(this)
}
onChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
handleSubmit(e) {
e.preventDefault();
this.post_flashcard()
}
async post_flashcard() {
const card = this.state;
const col_id = parseInt(this.state.collection_id)
try{
await axios.post(`http://127.0.0.1:8000/flashcardsapp/${col_id}`, card)
.then(response => console.log(response.status))
}catch(er){
console.log('ERROR in post_flashcard', er)
}
}
render() {
const {title, collection_id, term, definition} = this.state
return (
<form onSubmit={this.handleSubmit}>
<h2>Create a Card</h2>
<label for="title">Enter Collection Title</label>
<input type="text" name="title" value={title} onChange={this.onChange} ></input>
<label for="collection_id">Enter Collection ID</label>
<input type="number" name="collection_id" value={collection_id} onChange={this.onChange} ></input>
<label for="term">Enter Term</label>
<input type="text" name="term" value={term} onChange={this.onChange} ></input>
<label for="definition">Enter Definition</label>
<input type="text" name="definition" value={definition} onChange={this.onChange} ></input>
<input type="submit"></input>
</form>
);
}
}
export default CreateFlashCard;
【问题讨论】:
-
400 响应的正文是否包含任何有用的数据? 400 响应表示发送的数据存在某种问题,通常是数据验证问题
-
从服务器返回的实际错误是什么? 400 只是错误请求的状态码
-
我的东西是因为你的 body 包含
collection_id,所以你的服务器会抛出 400 错误。 -
在进行 axios 调用时是否登录/授权。有时 Django 会发送
400 Bad Request响应而不是401 Unauthorized。
标签: reactjs django axios components bad-request