这是一个 React 学校作业。该应用程序有两个输入字段和一个提交按钮。 OnClick,它发送一个带有输入值的 fetch post 请求。没有数据库,只有 JSON 文件存储值。请求顺利通过,但 JSON 文件中的正文为空。
其他细节:React 仍在渲染值之间的冒号。例如,它呈现“:”而不是“Christy:Post one”。输入字段正在工作;我可以在 React 开发工具中分辨出来,因为 onChange 他们正在更新状态。
我试过了:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
import React, { Component } from 'react';
class NewChirp extends Component {
constructor() {
super();
this.state = {
user: "",
text: ""
}
this.fetchChirps = this.fetchChirps.bind(this)
this.inputHandler = this.inputHandler.bind(this)
}
inputHandler(e) {
this.setState({ [e.target.name]: e.target.value })
}
fetchChirps() {
fetch('http://127.0.0.1:3000/api/chirps/', {
method: "POST",
contentType: "application/json; charset=utf-8",
// contentType: "application/x-www-form-urlencoded",
body: JSON.stringify({
user: this.state.user,
text: this.state.text,
})
})
.catch(err => console.log(err))
}
render() {
return (
<div>
<div className="input"></div>
<form action="">
<input
type="text"
placeholder="UserName"
size="10"
id="user"
name="user"
onChange={this.inputHandler}
defaultValue={this.state.user}
/>
<input
type="text"
placeholder="Type a new chirp"
size="60"
id="text"
name="text"
onChange={this.inputHandler}
defaultValue={this.state.text}
/>
<button onClick={this.fetchChirps} id="submit">Submit</button>
</form>
</div >
)
}
}
export default NewChirp;
最佳答案
看起来我只需要包装 contentType:
headers: {
"Content-Type": "application/json"
}
关于json - React fetch post 请求中的空属性和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52449304/