首页 > 解决方案 > 使用 Node.js 加载 GET 请求时收到 MongoClient Connection 错误响应

问题描述

每当我尝试通过 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

标签: node.jsmongodbexpressmongoosemongodb-atlas

解决方案


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

Mongoose 查询不是承诺。而是使用异步/等待

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

推荐阅读