我对NodeJS很陌生,我决定创建一个小型应用程序
我的项目结构非常简单,我有一个图书目录,当我点击添加图书按钮时,我会处理POST请求,然后将图书添加到数据库中
我想被动更新阵列的状态以显示我的新产品,但我必须关闭与服务器的连接,然后区域启用刷新我的页面,然后我会看到我新添加的产品。同时,我的POST请求的状态始终是pending
索引.vue
<div v-for="book in books" :key="book._id">
...
fetch("http://localhost:3000/addedBook", requestOptions)
.then(response => response.json())
.then(result => {
console.log(result)
})
.catch(error => console.log('error', error));
index.js
app.post('/addedBook', (req, res) => {
coll.insertOne(req.body, (err, res) => {
if (!err) {
mongoClient.close();
} else {
console.log('error', err)
}
});
索引.vue
fetch("/addedBook", requestOptions)
.then(response => response.json())
.then(result => {
this.books.push(result)
})
.catch(error => console.log('error', error));
索引.js
app.post('/addedBook', (req, res) => {
let db = mongo.db("books");
let collection = db.collection("books");
collection.insertOne(req.body, function (err, results) {
if (err) {
res.send('');
return
}
res.send(req.body) //retruns the new document
})
})