无法在部署(Heroku)中连接到MongoDb:连接ECONNREFUSED 127.0.0.1:27017

时间:2019-12-09 17:34:25

标签: node.js mongodb heroku deployment

我的应用程序在本地运行良好,但是在Heroku上部署时,服务器(连接到数据库)没有运行。

通过阅读日志并进行SO浏览,我认为是由于以下原因:

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/shareable-todo-new')
    .then((res) => console.log(res)).catch((err) => console.log(err));

我的package.json:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./app.js",
"dev": "nodemon ./app.js",
"heroku-postbuild":"NPM_CONFIG_PRODUCTION=false npm install --prefix front && npm run build --prefix front"
},

试图将其添加到我的package.json中,但没有帮助:

 "heroku config":"set NPM_CONFIG_PRODUCTION=true"

我的app.js:

const express = require('express')
const https = require('https')
const app = express();
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const path = require('path')

const routerLists = require('./routes/lists');
const routerTasks = require('./routes/tasks')
const routerUsers = require('./routes/users')

mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/shareable-todo-new', { useNewUrlParser: true, useUnifiedTopology: true })
        .then((res) => console.log(res)).catch((err) => console.log(err));
// fix a deprecated bugs
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.Promise = global.Promise;

// Serve static assets if In Production:
app.use(bodyParser.json())
app.use('/api', routerLists)
app.use('/api', routerTasks)
app.use('/api', routerUsers)

if(process.env.NODE_ENV === 'production'){
    // set static folder:
    app.use(express.static(path.join(__dirname, "front/build")))
    app.get("*", (req,res) => {
        res.sendFile(path.resolve(__dirname, 'front', 'build', 'index.html'))
    })
}
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });
// middleware para admitir errores:
app.use((err,res) => {
    res.status(422).send({
        error: err.message
    })
})
app.listen(process.env.PORT || 4000, () => console.log('express listening now...'))

如果有帮助,当我尝试执行POST请求时,chrome控制台会给出错误500

2 个答案:

答案 0 :(得分:0)

引用127.0.0.1(或localhost)表示您的本地计算机。在Heroku上运行应用程序时,Heroku机器是127.0.0.1,其中不包含MongoDB实例。您应该使用外部服务器托管MongoDB,例如https://mlab.com/

将MongoDB部署到服务器后,将环境变量(MONGODB_URI)设置为适当的值

答案 1 :(得分:0)

在本地PC(本地主机或127.0.0.1)上进行开发和测试时,您可以在端口27017(或任何其他端口)上本地设置代码,开发环境,服务器和MongoDB实例。但是,当您将代码部署到Heroku并尝试运行您的应用程序时,Heroku肯定会引发某种错误,因为它尚未在服务器(即.herokuapp.com)上配置任何MongoDB实例。如果您找到一种创建实例非常困难的方法,那就很好了。

推荐的最佳方法是将您的应用程序连接到MongoDB云。如Oleksandr的上述回答所述,您必须在mlab或MongoDB Atlas上创建一个帐户。

将以下代码段放置在存在用于启动服务器的代码的javascript文件中。

//the following URL will be provided once you create an account on MongoDB Atlas and create 
//a cluster. 
mongoose.connect(`mongodb+srv://<database_user_name>:<password>@cluster.address/<db_name>?retryWrites=true&w=majority`,{
    useNewUrlParser:true,
    useUnifiedTopology:true //this line is not mandatory
}).then(()=>{
    console.log('Connected to MongoDB Cloud :)');
})//catch errors if you want.

如果您从localhost:port在MongoDB云上开发并进行CRUD操作,其他CRUD操作应该可以正常工作,并确保您具有良好的Internet连接。

那应该有所帮助! :)

相关问题