使用Node.js加载GET请求时收到MongoClient Connection错误响应

时间:2019-09-04 07:06:19

标签: node.js mongodb express mongoose mongodb-atlas

每当我尝试通过Postman上的GET请求获取数据时,都会收到此MongoDB Atlas连接错误,这种错误并不总是在POST请求中发生。我刚刚开始这一旅程。非常感谢您的帮助。

const express = require('express');
const mongoose = require('mongoose');

const router = express.Router();
const Product = require('../model/product');

router.get('/', (req, res, next) => {
    Product.find()
    .exec()
    .then(docs=>{
        console.log(docs);
        res.status(200).json(docs);
    })
    .catch(err=>{
        console.log(err);
        res.status(500).json({error:err}); 

    }); 
});  




router.post('/', (req, res, next) => {


    const product = new Product({
        _id: mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    });

    product.save().then(result=>{
        console.log(result);
    })
    .catch(err=> console.log(err)); 




    res.status(200).json({
        message:'Products Added!!! ',
        createdProduct: product
    });
});

我总是会收到此错误:

Could not get any response
There was an error connecting to.
Why this might have happened:
The server couldn't send a response:
Ensure that the backend is working properly
Self-signed SSL certificates are being blocked:
Fix this by turning off 'SSL certificate verification' in Settings > General
Proxy configured incorrectly
Ensure that proxy is configured correctly in Settings > Proxy
Request timeout:
Change request timeout in Settings > General

1 个答案:

答案 0 :(得分:0)

如果您查看文档https://mongoosejs.com/docs/queries.html

猫鼬查询不是承诺。而是使用async / await

router.get("/", async (req,res)=>{
   const docs=await Product.find().sort("name")
   res.status(200).send(docs)
})