node.js - [ 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 集合中存在一些项目并且它在我的本地环境中工作。
谢谢你。
解决方案
您正在运行 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 设置了配置变量。
推荐阅读
- c++ - 如何将文件中的每个字符加倍?
- vue.js - vue中的列表渲染
- r - 使用 Shiny flyio 的 s3 身份验证错误
- python - 扩展应用程序时 concurrent.futures.ThreadPoolExecutor max workers 的工作
- php - 通过 phpmailer 发送电子邮件的重定向过多
- flutter - Flutter DropdownButton 不会在 StatefulBuilder 中更新
- c# - C#中接口的工作流
- adsense - 启用跨域隔离后 Google Ads 不显示
- arrays - 迭代对象数组
- mathematical-optimization - 如何将条件二进制变量添加到 GUROBI