【发布时间】:2018-04-22 15:37:43
【问题描述】:
我正在尝试制作一个 React-Node.js 应用程序以供练习。我在发送 POST 请求时遇到问题。当我在 App.js 中获取 POST 请求时,它只返回 id。我预计它会返回 3 个以上的值。
当前对象
{ _id: 5a046d52bb5d37063b3c8b21 }
理想对象
{_id: "59e9fed60fe8bf0d7fd4ac6e", name: "recipe1", ingredients: "apple", descriptions: "cut an apple"}
我应该如何正确地向 req.body 添加值?我提到了这个解决方案Post an object with fetch using react js and express API server,但它不适用于我的应用程序。
index.js (node.js)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(bodyParser.urlencoded({ extended: true}));
var db
const MongoClient = require('mongodb').MongoClient
MongoClient.connect
('mongodb://Recipe:recipebox@ds125914.mlab.com:25914/ayumi', (err, database) => {
if (err) return console.log(err)
db = database
app.listen(8080, () => {
console.log('listening on 8080')
})
})
app.get('/api', (req,res)=> {
db.collection('recipe').find().toArray((err, results) => {
if(err) return console.log("no recipe");
res.json(results);
})
})
app.post('/recipe', (req,res)=>{
db.collection('recipe').save(req.body, (err, result) => {
if(err) return console.log(err);
console.log(req.body)
console.log('save to database');
res.redirect('/');
})
})
App.js(反应)
class App extends Component {
constructor(props){
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e){
e.preventDefault();
fetch('/recipe', {
method: 'POST',
body: JSON.stringify({
name: this.refs.name.value,
ingredients: this.refs.ingredients.value,
descriptions: this.refs.descriptions.value
}),
headers: {"Content-Type" : "application/json"}
})
.then((res)=> {
return res.json()
})
.then((body)=>{
console.log("body" + body)
console.log("result" + this.refs.name.value)
})
}
render() {
return (
<div className="App">
<h1>Recipe List</h1>
<form onSubmit={this.handleSubmit}>
<input type="text" placeholder="name" ref="name" />
<input type="text" placeholder="ingredients" ref="ingredients" />
<input type="text" placeholder="descriptions" ref="descriptions" />
<input type="submit"/>
</form>
</div>
)
}
}
导出默认应用;
【问题讨论】:
-
我很惊讶你得到 anything 考虑到 POST 方法服务器端只是以重定向结束并且从不使用
result值(可能包含你新创建的数据对象)。你看到值被写入数据库吗? -
未添加值。每个对象只包含像
{"_id":"5a0472c56f37cb06a4c8f54c"}]这样的 id -
但是每次添加配方时,
recipe集合中都会有一个新条目,其中只有_id字段集,对吗? -
console.log(req.body)中的app.post显示什么? -
显示
listening on 8080 { _id: 5a0472c56f37cb06a4c8f54c } save to database
标签: node.js reactjs express fetch