node.js - MongoDB Node Express GET 和 DELETE 工作,而不是 POST?
问题描述
GET 工作。删除作品。
无法弄清楚为什么 POST 不能使用像这样简单的东西。
{"akey":"avalue"}
使用 Postman 进行测试。Postman 的错误是“无法得到任何响应”,这很奇怪,因为我对 GET 和 DELETE 没有任何问题。
Mongo/Node 的新手。遵循 Brad Traversy关于 Vue、Mongo、Express、Node的https://www.youtube.com/watch?v=j55fHUJqtyw教程。
有什么突出的吗?
const express = require( 'express' );
const mongodb = require( 'mongodb' );
const router = express.Router();
// GET POSTS
router.get( '/', async ( req, res ) => {
const posts = await loadPostsCollection();
res.send( await posts.find( {} ).toArray() );
} );
// ADD POST
router.post( '/', async ( req, res ) => {
const posts = await loadPostsCollection();
await posts.insertOne( {
text: req.body.text
} );
res.status(201).send();
} );
// DEL POST
router.delete('/:id', async (req, res)=>{
const posts = await loadPostsCollection();
await posts.deleteOne({_id: new mongodb.ObjectID(req.params.id)});
res.status(200).send();
})
async function loadPostsCollection() {
const client = await mongodb.MongoClient.connect( 'mongodb+srv://someUser:somePassword@some-bkebp.mongodb.net/test?retryWrites=true&w=majority', {
useNewUrlParser : true,
useUnifiedTopology: true
} );
return client.db( 'someDB' ).collection( 'somCollection' )
}
module.exports = router;
解决方案
原因
似乎你的await posts.insertOne({ text: req.body.text });
永无止境(或崩溃和快递没有响应),所以邮递员永远不会得到响应。
尝试console.log
在你之后await
查看它是否是问题的根本原因。
可能的解决方案
尝试以这种方式处理有关您的数据库请求的错误
router.post('/', async (req, res) => {
try {
const posts = await loadPostsCollection();
await posts.insertOne({
text: req.body.text
});
res.status(201).send(); // You may need to answer something here
} catch (e) {
console.error(e);
return res.status(500).end() // 500 is INTERNAL SERVER ERROR
}
});
推荐阅读
- python - 是否有一个函数可以在熊猫中分隔列的末尾去除空值
- raspberry-pi - 如何通过互联网在多个树莓派之间进行通信?
- java - Java反射与非反射性能比较
- javascript - 如何使用 g2plot 实现梯度雷达
- android - 为什么我不能将我的颤振应用程序用作服务器?
- python - BeautifulSoup 不在标签中显示标签
- javascript - 了解 Javascript 中的 IIFE 范围
- neural-network - 为什么演员神经网络不学习?
- html - PrimeNG - p-tree 的新 p-splitter 组件未填满空间
- java - 当类型为 Foo 时如何反序列化 response.readEntity()
并有一个属性 List