首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将heroku服务器连接到mongodb?

如何将heroku服务器连接到mongodb?
EN

Stack Overflow用户
提问于 2019-08-07 05:45:09
回答 1查看 4.2K关注 0票数 1

作为node.js的初学者,我有一个在heroku上部署服务器的问题。

我做了一个使用mongodb的server.js应用程序。当我使用"npm start“cmd在本地(http://localhost:3000)上运行服务器时,它工作得很好,我可以通过以下命令连接到我的mongo数据库:

代码语言:javascript
复制
mongoose.connect(
'mongodb+srv://yolanpibrac:mypassword@cluster0-7z1th.mongodb.net/test?                        retryWrites=true&w=majority';, 
{ useNewUrlParser: true })  

(我遵循了这个教程:[https://appdividend.com/2018/04/14/how-to-deploy-nodejs-app-to-heroku/])

但是当我在heroku上部署我的应用程序时,该应用程序无法连接到mongo db。我有以下错误(通过检查: heroku logs -t):

代码语言:javascript
复制
2019-08-06T21:06:33.086146+00:00 heroku[web.1]: Starting process with     command `node src/server.js`
2019-08-06T21:06:35.404641+00:00 heroku[web.1]: State changed from     starting to up
2019-08-06T21:06:35.058357+00:00 app[web.1]: Listening on port 26845
2019-08-06T21:06:36.144056+00:00 app[web.1]: Error while DB connecting
2019-08-06T21:06:36.149809+00:00 app[web.1]: { MongoNetworkError: failed     to connect to server [cluster0-shard-00-00-7z1th.mongodb.net:27017] on first     connect [MongoNetworkError: connection 5 to cluster0-shard-00-00-    7z1th.mongodb.net:27017 closed]
2019-08-06T21:06:36.149812+00:00 app[web.1]: at Pool.<anonymous>     (/app/node_modules/mongodb-core/lib/topologies/server.js:431:11)
2019-08-06T21:06:36.149814+00:00 app[web.1]: at Pool.emit     (events.js:189:13)
2019-08-06T21:06:36.149815+00:00 app[web.1]: at connect     (/app/node_modules/mongodb-core/lib/connection/pool.js:557:14)
2019-08-06T21:06:36.149816+00:00 app[web.1]: at callback     (/app/node_modules/mongodb-core/lib/connection/connect.js:109:5)
2019-08-06T21:06:36.149818+00:00 app[web.1]: at runCommand     (/app/node_modules/mongodb-core/lib/connection/connect.js:129:7)
2019-08-06T21:06:36.149819+00:00 app[web.1]: at Connection.errorHandler     (/app/node_modules/mongodb-core/lib/connection/connect.js:321:5)
2019-08-06T21:06:36.149820+00:00 app[web.1]: at Object.onceWrapper     (events.js:277:13)
2019-08-06T21:06:36.149821+00:00 app[web.1]: at Connection.emit     (events.js:189:13)
2019-08-06T21:06:36.149823+00:00 app[web.1]: at TLSSocket.<anonymous>     (/app/node_modules/mongodb-core/lib/connection/connection.js:350:12)
2019-08-06T21:06:36.149824+00:00 app[web.1]: at Object.onceWrapper     (events.js:277:13)
2019-08-06T21:06:36.149825+00:00 app[web.1]: at TLSSocket.emit     (events.js:189:13)
2019-08-06T21:06:36.149826+00:00 app[web.1]: at _handle.close     (net.js:613:12)
2019-08-06T21:06:36.149828+00:00 app[web.1]: at TCP.done     (_tls_wrap.js:386:7)
2019-08-06T21:06:36.149829+00:00 app[web.1]: name: 'MongoNetworkError',
2019-08-06T21:06:36.149830+00:00 app[web.1]: errorLabels: [     'TransientTransactionError' ],
2019-08-06T21:06:36.149832+00:00 app[web.1]:     [Symbol(mongoErrorContextSymbol)]: {} }

我已经阅读了与这个问题相关的所有问题,但没有一个解决方案起作用。我有mongodb账号和集群连接字符串,我在我的密码中很小心,任何特殊的字符都是URL编码的。我有一个procfile : web: node src/server.js和一个index.html文件

我的server.js文件:

代码语言:javascript
复制
//Définition des modules
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require('body-parser');
const app = express();
const path = require('path');



const dbRoute = 'mongodb+srv://yolanpibrac:mypassword@cluster0-    7z1th.mongodb.net/test?retryWrites=true&w=majority';
const dbRouteLocal = 'mongodb://localhost/db';
//Connexion à la base de donnée
mongoose.connect(dbRoute, { useNewUrlParser: true }).then(() => {
    console.log('Connected to mongoDB')
}).catch(e => {
    console.log('Error while DB connecting');
    console.log(e);
});



var urlencodedParser = bodyParser.urlencoded({
    extended: true
});
app.use(urlencodedParser);
app.use(bodyParser.json({limit: '10mb', extended: true}));

//Définition des CORS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-    With,content-type,Accept,content-type,application/json');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS,     PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});



var router = express.Router();
app.use('/user', router);
require(__dirname + '/controllers/userController')(router);


app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});
app.get('*', function(req, res) {
    res.sendFile(path.join(__dirname, 'index.html'));
});

//Définition et mise en place du port d'écoute
var port = process.env.PORT || "3000";

app.listen(port, () => console.log(`Listening on port ${port}`));

我的package.json:

代码语言:javascript
复制
{
  "name": "movies-displayer",
  "version": "0.1.0",
  "engines": {
    "node": "11.4.0"
  },
  "private": true,
  "proxy": "http://yolan-pibrac.com",
  "dependencies": {
    "animated": "^0.2.2",
    "axios": "^0.19.0",
    "body-parser": "^1.19.0",
    "bootstrap": "^4.3.1",
    "express": "^4.17.1",
    "jwt-simple": "^0.5.6",
    "mongodb": "^3.3.0-beta2",
    "mongoose": "^5.6.8",
    "password-hash": "^1.2.2",
    "react": "^16.8.6",
    "react-activity": "^1.2.2",
    "react-animations": "^1.0.0",
    "react-bootstrap": "^0.32.1",
    "react-bootstrap-dropdown-menu": "^1.1.15",
    "react-dom": "^16.8.6",
    "react-multi-carousel": "^2.1.2",
    "react-popper": "^1.3.3",
    "react-pose": "^4.0.8",
    "react-redux": "^7.0.3",
    "react-router": "^4.3.1",
    "react-router-dom": "^4.3.1",
    "react-scripts": "3.0.1",
    "react-state-animation": "^0.1.0",
    "reactstrap": "^8.0.1",
    "redux": "^4.0.1",
    "styled-components": "^4.3.2"
  },
  "scripts": {
    "start": "node src/server.js"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我可以提供更多的细节,如果需要!谢谢你的帮助,

EN

回答 1

Stack Overflow用户

发布于 2019-08-07 06:40:13

您可能需要允许heroku访问您的mongodb服务器。

您可以登录到Mongodb atlas并单击左侧安全设置下的Network access,然后单击右上角的add ip address并输入0.0.0.0/0作为ip地址,以允许从所有ip a或添加您的heroku服务器的特定ip进行访问。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57384411

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档