简体   繁体   English

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

[英]How to connect heroku server to mongodb?

Beginner with node.js I have an issue to deploy server on heroku. node.js 初学者我在 heroku 上部署服务器时遇到问题。

I made a server.js application which use mongodb.我制作了一个使用 mongodb 的 server.js 应用程序。 It's work fine when I run the server on local ( http://localhost:3000 ) with "npm start" cmd, I'm able to connect to my mongo database by the command :当我使用“npm start”cmd 在本地( http://localhost:3000 )上运行服务器时,它工作正常,我可以通过以下命令连接到我的 mongo 数据库:

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

(I followed this tutorial : [ https://appdividend.com/2018/04/14/how-to-deploy-nodejs-app-to-heroku/] ) (我遵循了本教程:[ https://appdividend.com/2018/04/14/how-to-deploy-nodejs-app-to-heroku/]

But when i deploy my app on heroku, the app can not connect to mongo db.但是当我在 heroku 上部署我的应用程序时,该应用程序无法连接到 mongo db。 I have the following error (by checking : heroku logs -t) :我有以下错误(通过检查:heroku logs -t):

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)]: {} }

I already read all issues related to this problem, but none of the solution worked.我已经阅读了与此问题相关的所有问题,但没有一个解决方案有效。 I have mongodb account with cluster connexion string I was carefull in my password that any special characters are URL encoded.我有带有集群连接字符串的 mongodb 帐户,我在密码中很小心,任何特殊字符都是 URL 编码的。 I have a procfile : web: node src/server.js and an index.html file我有一个 procfile : web: node src/server.js 和一个 index.html 文件

my server.js file :我的 server.js 文件:

//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}`));

my package.json :我的 package.json :

{
  "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"
    ]
  }
}

I can provide more details if needed !如果需要,我可以提供更多详细信息! Thank you for your help,感谢您的帮助,

You may need to allow heroku to access your mongodb server.您可能需要允许 heroku 访问您的 mongodb 服务器。

You can do this by logging in to Mongodb atlas and clicking on Network access on the left side under security settings, then click add ip address on the right top and enter 0.0.0.0/0 as the ip address to allow access from all ip's a or add your heroku servers' specific ip if you can get it.您可以通过登录Mongodb图集并单击安全设置下左侧的网络访问,然后单击右上角的添加ip地址并输入0.0.0.0/0作为ip地址来允许所有ip的访问来做到这一点或者如果可以的话,添加您的heroku服务器的特定IP。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM