首页 > 解决方案 > [ MongoNetworkError ],当我在 Heroku 上部署时,应用程序无法连接到 mongoDB

问题描述

我使用 mongoDB、Express、React 和 Node 创建了全栈购物清单应用程序(与待办事项清单基本相同)。它适用于我的本地环境。但是当我尝试在 Heroku 上运行应用程序时,我得到了 mongoDB 连接错误。它说 :

{ MongoNetworkError: connection 5 to cluster0-shopping-list-2-shard-00-02-0rerl.mongodb.net:27017 closed
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }

我使用 mongoDB Atlas,并且我已经在 Atlas 上的集群中将我的 IP 地址设置为白名单。

这是我的代码:

配置/keys.js

module.exports = {
    mongoURI: 'mongodb+srv://<Username>:<myUserPassword>3@cluster0-shopping-list-2-0rerl.mongodb.net/test?retryWrites=true'
}

服务器.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
const items = require('./routes/api/items');
const app = express();

// Body-parser Middleware
app.use(bodyParser.json());

// db config
const db = require('./config/keys').mongoURI;

// connect to Mongo
mongoose
    .connect(db, { useNewUrlParser: true})
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err));

// Use Routes
app.use('/api/items', items)

// Serve static assets if in production
if(process.env.NODE_ENV === 'production'){
    // Set static folder
    app.use(express.static('client/build'));

    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
    });
}

const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server is running on port ${port}.`));

package.json (我展示这个是因为这可能与这个问题有关。)

"scripts": {
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
  },

我希望应用程序显示 mongoDB 集合具有的项目列表。我想允许用户添加新项目。但它没有显示任何项目,即使我可以看到 MongoDB 集合中存在一些项目并且它在我的本地环境中工作。
谢谢你。

标签: node.jsreactjsmongodbherokuredux

解决方案


您正在运行 npm run server and client 但您的 package.json 中未定义服务器和客户端脚本

"scripts": {
    "server": "nodemon server/server.js",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\""
  }

您是否在项目的 heroku 设置中为数据库连接 mongoURI 和 PORT 设置了配置变量。


推荐阅读