gpt4 book ai didi

node.js - [ MongoNetworkError ],当我在 Heroku 上部署时,应用程序无法连接到 mongoDB

转载 作者:太空宇宙 更新时间:2023-11-04 01:30:22 24 4
gpt4 key购买 nike

我使用 mongoDB、Express、React 和 Node 创建了全栈购物 list 应用程序(基本上与待办事项列表相同)。它适用于我本地的环境。但是当我尝试在 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,并且我已经将我的IP地址设置为Atlas集群中的白名单。

这是我的代码:

config/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 服务器和客户端,但 package.json 中未定义服务器和客户端脚本

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

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

关于node.js - [ MongoNetworkError ],当我在 Heroku 上部署时,应用程序无法连接到 mongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56313096/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com