首页 > 解决方案 > 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;

标签: node.jsmongodbexpress

解决方案


原因

似乎你的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
  }
});

推荐阅读