node.js - 使用 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
解决方案
如果您查看文档https://mongoosejs.com/docs/queries.html
Mongoose 查询不是承诺。而是使用异步/等待
router.get("/", async (req,res)=>{
const docs=await Product.find().sort("name")
res.status(200).send(docs)
})
推荐阅读
- c# - 如何在 LINQ 查询中使用从 Request.Query 获得的多值/数组参数(枚举值)?
- r - 在 Linux 上升级 R 时会删除软件包吗?
- javascript - 从 React 数组中过滤过期卡片
- json - 如何从clojure中的字符串中获取每个json对象?
- tensorflow - 批量标准化会破坏验证性能
- python - 从数组的每一行创建一个对象
- java - 使用 Spring webflow 处理外部身份验证流
- multithreading - 如何保持线程的消息泵反应
- firebase - Google Firebase 无法验证 Domain.com 域的所有权
- javascript - 如何在函数中添加 2 个事件侦听器并返回发生的事件?