【问题标题】:MongoDB Node Express GET and DELETE work, not POST?MongoDB Node Express GET 和 DELETE 工作,而不是 POST?
【发布时间】:2020-02-21 17:48:32
【问题描述】:

GET 有效。 DELETE 有效。

无法弄清楚为什么 POST 不能使用像这样简单的东西。

{"akey":"avalue"}

使用 Postman 进行测试。 Postman 的错误是“Could not get any response”,这很奇怪,因为我对 GET 和 DELETE 没有任何问题。

Mongo/Node 的新手。按照 Brad Traversy 的 https://www.youtube.com/watch?v=j55fHUJqtyw 教程,了解 Vue、Mongo、Express、Node。

有什么突出的吗?

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.js mongodb express


    【解决方案1】:

    原因

    您的 await posts.insertOne({ text: req.body.text }); 似乎永远不会结束(或者崩溃并且 express 没有响应),所以 Postman 永远不会得到响应。

    await 之后尝试console.loging,看看它是否是问题的根本原因。

    可能的解决方案

    尝试以这种方式处理有关您的数据库请求的错误

    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
      }
    });
    

    【讨论】:

      【解决方案2】:

      如果您可以放置​​一些逻辑来处理错误,那么那里可能会有有用的信息。

      // ADD POST
      router.post( '/', async ( req, res ) => {
          const posts = await loadPostsCollection();
          await posts.insertOne( {
                                 text: req.body.text
                             })
          .then(result => if (result) res.status(201).send());  // handle success case
          .catch(err => { //see what the error is
              console.error; 
              res.status(500)
              res.render('error', { error: err })
              })
      });
      

      【讨论】:

      • 不幸的是,它仍然超时,最后我得到的只是“无法得到任何响应”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 2013-05-17
      • 1970-01-01
      • 2022-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多