我正在编写一个程序,该程序使用 React 作为前端,并使用 Express/Node API 作为后端,然后在 MongoDB 数据库中执行 CRUD 操作。现在,我正在使用 native JS fetch() API 在前端执行 GET/POST 操作。 GET 请求工作正常,但我的 POST 请求似乎不起作用。在我的前端,我有一个表单和一个用于表单提交的处理程序,如下所示:
handleSubmit(){
let databody = {
"name": this.state.nameIn,
"quote": this.state.quoteIn
}
return fetch('http://localhost:5002/stored', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name
<input type="text" name="name" value={this.nameIn} onChange={this.handleNameChange}/>
</label>
<label>
quote
<input type="text" name="quote" value={this.quoteIn} onChange={this.handleQuoteChange}/>
</label>
<input type="submit" value="Add to DB" />
</form>
</div>
);
}
然后在端口 5002 上的 Express API 上,我有:
app.post('/stored', (req, res) => {
console.log(req.body);
db.collection('quotes').insertOne(req.body, (err, data) => {
if(err) return console.log(err);
res.send(('saved to db: ' + data));
})
});
但是,提交表单后,请求会显示在 Express API 上,且正文为空。 console.log 显示 req.body 只是一个 { } 我想知道我做错了什么?
最佳答案
使用body-parser
在您的快速代码中添加:
global.bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true,
limit: '50mb',
parameterLimit: 100000
}))
app.use(bodyParser.json({
limit: '50mb',
parameterLimit: 100000
}))
app.post('/stored', (req, res) => {
console.log(req.body);
db.collection('quotes').insertOne(req.body, (err, data) => {
if(err) return console.log(err);
res.send(('saved to db: ' + data));
})
});
在你的前端:
handleSubmit:function(e){
e.preventDefault();
let databody = {
"name": this.state.nameIn,
"quote": this.state.quoteIn
}
fetch('http://localhost:5002/stored', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
关于node.js - 使用 Express/Node 和 MongoDB 响应 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50617351/