node.js应用程序可在本地工作,但在heroku上部署时会崩溃

时间:2020-08-18 23:00:38

标签: mysql node.js heroku npm

过去的几天,我一直在尝试在Heroku上部署我的应用程序,但是没有运气。该应用程序在本地运行完美,heroku能够显示我的应用程序的主登录页面,但是,一旦我单击导航栏中的链接之一,它就会崩溃。下面是我得到的错误日志:

2020-08-18T22:41:00.087725+00:00 heroku[web.1]: State changed from up to starting
2020-08-18T22:41:01.392738+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2020-08-18T22:41:01.650382+00:00 heroku[web.1]: Process exited with status 143
2020-08-18T22:41:02.631432+00:00 heroku[web.1]: Starting process with command `npm start`
2020-08-18T22:41:05.144391+00:00 app[web.1]: 
2020-08-18T22:41:05.144412+00:00 app[web.1]: > cinewatch@1.0.0 start /app
2020-08-18T22:41:05.144413+00:00 app[web.1]: > node app.js
2020-08-18T22:41:05.144413+00:00 app[web.1]: 
2020-08-18T22:41:05.462534+00:00 app[web.1]: Express started on port 20048; press Ctrl-C to terminate.
2020-08-18T22:41:05.586508+00:00 heroku[web.1]: State changed from starting to up
2020-08-18T22:41:26.813493+00:00 heroku[router]: at=info method=GET path="/" host=cine-test.herokuapp.com request_id=8d9fa52f-f684-4184-8952-b52b872279e7 fwd="73.223.2.138" dyno=web.1 connect=0ms service=49ms status=304 bytes=152 protocol=https
2020-08-18T22:41:27.020721+00:00 heroku[router]: at=info method=GET path="/css/style.css" host=cine-test.herokuapp.com request_id=b416deb5-d5b6-4e1d-856d-3806b8b4407b fwd="73.223.2.138" dyno=web.1 connect=0ms service=7ms status=200 bytes=1650 protocol=https
2020-08-18T22:41:27.114408+00:00 heroku[router]: at=info method=GET path="/logo.png" host=cine-test.herokuapp.com request_id=f7fbd636-4d82-42b8-96b5-67cbaf099fcf fwd="73.223.2.138" dyno=web.1 connect=0ms service=2ms status=200 bytes=10805 protocol=https
2020-08-18T22:41:27.316012+00:00 heroku[router]: at=info method=GET path="/theatre2.jpg" host=cine-test.herokuapp.com request_id=71d193fa-b5ee-476c-adcc-d17f70d2097d fwd="73.223.2.138" dyno=web.1 connect=0ms service=116ms status=200 bytes=1594986 protocol=https
2020-08-18T22:41:27.321207+00:00 heroku[router]: at=info method=GET path="/theatre3.jpg" host=cine-test.herokuapp.com request_id=3e0d1d33-5017-4e96-9430-461c8e68ee7d fwd="73.223.2.138" dyno=web.1 connect=1ms service=116ms status=200 bytes=1341680 protocol=https
2020-08-18T22:41:27.361564+00:00 heroku[router]: at=info method=GET path="/theatre1.jpg" host=cine-test.herokuapp.com request_id=596e2c08-948e-499d-bff1-6cf00ce160d4 fwd="73.223.2.138" dyno=web.1 connect=1ms service=163ms status=200 bytes=3699945 protocol=https
2020-08-18T22:41:28.152538+00:00 app[web.1]: /app/routes/awards.routes.js:20
2020-08-18T22:41:28.152554+00:00 app[web.1]:                     throw(err);
2020-08-18T22:41:28.152555+00:00 app[web.1]:                     ^
2020-08-18T22:41:28.152555+00:00 app[web.1]: 
2020-08-18T22:41:28.152557+00:00 app[web.1]: Error: connect ECONNREFUSED 127.0.0.1:3306
2020-08-18T22:41:28.152557+00:00 app[web.1]:     at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)
2020-08-18T22:41:28.152558+00:00 app[web.1]:     --------------------
2020-08-18T22:41:28.152558+00:00 app[web.1]:     at Protocol._enqueue (/app/node_modules/mysql/lib/protocol/Protocol.js:144:48)
2020-08-18T22:41:28.152559+00:00 app[web.1]:     at Protocol.handshake (/app/node_modules/mysql/lib/protocol/Protocol.js:51:23)
2020-08-18T22:41:28.152559+00:00 app[web.1]:     at PoolConnection.connect (/app/node_modules/mysql/lib/Connection.js:116:18)
2020-08-18T22:41:28.152560+00:00 app[web.1]:     at Pool.getConnection (/app/node_modules/mysql/lib/Pool.js:48:16)
2020-08-18T22:41:28.152560+00:00 app[web.1]:     at Pool.query (/app/node_modules/mysql/lib/Pool.js:202:8)
2020-08-18T22:41:28.152561+00:00 app[web.1]:     at Query._callback (/app/routes/awards.routes.js:18:24)
2020-08-18T22:41:28.152561+00:00 app[web.1]:     at Query.Sequence.end (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
2020-08-18T22:41:28.152561+00:00 app[web.1]:     at /app/node_modules/mysql/lib/Pool.js:205:13
2020-08-18T22:41:28.152562+00:00 app[web.1]:     at Handshake.onConnect (/app/node_modules/mysql/lib/Pool.js:58:9)
2020-08-18T22:41:28.152562+00:00 app[web.1]:     at Handshake.<anonymous> (/app/node_modules/mysql/lib/Connection.js:526:10) {
2020-08-18T22:41:28.152562+00:00 app[web.1]:   errno: 'ECONNREFUSED',
2020-08-18T22:41:28.152563+00:00 app[web.1]:   code: 'ECONNREFUSED',
2020-08-18T22:41:28.152563+00:00 app[web.1]:   syscall: 'connect',
2020-08-18T22:41:28.152564+00:00 app[web.1]:   address: '127.0.0.1',
2020-08-18T22:41:28.152564+00:00 app[web.1]:   port: 3306,
2020-08-18T22:41:28.152565+00:00 app[web.1]:   fatal: true
2020-08-18T22:41:28.152565+00:00 app[web.1]: }
2020-08-18T22:41:28.163244+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-08-18T22:41:28.163621+00:00 app[web.1]: npm ERR! errno 1
2020-08-18T22:41:28.166002+00:00 app[web.1]: npm ERR! cinewatch@1.0.0 start: `node app.js`
2020-08-18T22:41:28.166148+00:00 app[web.1]: npm ERR! Exit status 1
2020-08-18T22:41:28.166314+00:00 app[web.1]: npm ERR! 
2020-08-18T22:41:28.166455+00:00 app[web.1]: npm ERR! Failed at the cinewatch@1.0.0 start script.
2020-08-18T22:41:28.166586+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-08-18T22:41:28.175255+00:00 app[web.1]: 
2020-08-18T22:41:28.175419+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-08-18T22:41:28.175496+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-08-18T22_41_28_168Z-debug.log
2020-08-18T22:41:28.224720+00:00 heroku[web.1]: Process exited with status 1
2020-08-18T22:41:28.268272+00:00 heroku[web.1]: State changed from up to crashed
2020-08-18T22:41:28.270673+00:00 heroku[web.1]: State changed from crashed to starting
2020-08-18T22:41:28.158365+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=GET path="/awards" host=cine-test.herokuapp.com request_id=fa9a6af8-7992-47d5-9857-8ad1133dc1c2 fwd="73.223.2.138" dyno=web.1 connect=0ms service=22ms status=503 bytes=0 protocol=https

下面是文件和文件夹结构:

- node_modules
- routes
    - example.routes.js
    - etc...
- static (contains css and js files)
- views
    - layouts
        - main.handlebars (main html layout of all pages)
    - partials
        - navbar.handlebars (navbar that appears in all pages)
    - example.handlebars
    - etc...
- .env
- .gitignore
- app.js
- dbcon.js
- package.json
- package-lock.json

app.js:

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config();
}

const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');
const mysql = require('./dbcon.js');
const bodyParser = require('body-parser');
const moment = require('moment');

// constants
const port = process.env.PORT || 9716;
const app = express();

// set up handlebars
var hbs = exphbs.create({
    layoutsDir: path.join(__dirname, 'views/layouts'),
    defaultLayout:'main',
    partialsDir: path.join(__dirname, 'views/partials'),
    helpers: {
        moment: require('helper-moment'),
        getAge: function (dobString) {
            if(dobString == null) {
                return "Unknown";
            }
            let dob = moment(dobString);
            let now = moment().local();
            let age = moment.duration(now.diff(dob));
            return Math.floor(age.asYears());
        },
        yearOnly: function (dateString) {
            let date = moment(dateString).local();
            date.set({hours:0,minutes:0,seconds:0});
            return date.year();
        }
    }
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

//set up body parser
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// set up file location for static files
app.use(express.static(path.join(__dirname, 'static')));

app.get('/', function (req, res, next) {
    let context = {
        message: "Welcome to CineWatch!"
    };
    res.render('home', context);
});

// routes
app.use('/genres', require('./routes/genres.routes.js'));
app.use('/actors', require('./routes/actors.routes.js'));
app.use('/genremovies', require('./routes/genremovies.routes.js'));
app.use('/actormovies', require('./routes/actormovies.routes.js'));
app.use('/movies', require('./routes/movies.routes.js'));
app.use('/theatres', require('./routes/theatres.routes.js'));
app.use('/awards', require('./routes/awards.routes.js'));
app.use('/theatresmovies', require('./routes/theatresmovies.routes.js'));

// start app
app.listen(port, function(){
    console.log('Express started on port ' + port + '; press Ctrl-C to terminate.')
});

dbcon.js(数据库URL,名称和密码包含在.env文件中):

var mysql  = require('mysql');
var pool = mysql.createPool({
    connectionLimit : 10,
    host     : process.env.DB_URL,
    user     : process.env.DB_NAME,
    password : process.env.DB_PASSWORD,
    database : process.env.DB_NAME,
    port     : '3306'
});
module.exports.pool = pool;

awards.routes.js(已删除一些详细信息):

const express = require('express')
    , mysql = require('../dbcon.js')
    , router = express.Router();

const getAllAwardsData = (res) => {
    mysql.pool.query('', (err, rows, fields) => {
        if (err) {
            next(err);
            return;
        }
        res.json({rows: rows});
    })
}

router.route('/')
    .get(function (req, res, next) {
        mysql.pool.query("", [], (err, rows2) => {
            mysql.pool.query("", [], (err, rows) => {
                if (err) {
                    throw(err);
                } else {
                    let context = {
                        data: rows,
                        data2: rows2
                    };
                    res.render('awards', context);
                }
            });
        });
    })
    .post(function (req, res, next) {
        var context = {};
        var {} = req.body;
        if () {
            mysql.pool.query(" () VALUES ()", [], function(err, result) {
                if (err) {
                    next(err);
                    return;
                }
                getAllAwardsData(res);
            });
        } else {
            mysql.pool.query(" () VALUES ()", [], function(err, result) {
                if (err) {
                    next(err);
                    return;
                }
                getAllAwardsData(res);
            });
        }
    })
    .delete(function (req, res, next) {
        var context = {};
        var {} = req.body;
        mysql.pool.query("", [], function (err, result) {
            if (err) {
                next(err);
                return;
            }
            context.results = "Deleted row";
            res.send(context);
        });
    })
    .put(function (req, res, next) {
        var context = {};
        var {} = req.body;
        mysql.pool.query("", [], function(err, result) {
            if (err) {
                next(err);
                return;
            }
            context.results = "Updated row";
            res.send(context);
        });
    });

module.exports = router;

从我到目前为止收集的资料来看,问题似乎源于我的数据库。 Heroku可以顺利加载我的主页,但是当我尝试访问其他页面(所有页面都从我的数据库加载并显示数据)时,它崩溃了。感谢大家的帮助!

2 个答案:

答案 0 :(得分:0)

错误消息指示'/app/routes/awards.routes.js'中的错误 在第20行 建立联系可能有些错误 你能把它的代码

答案 1 :(得分:0)

这是错误中重要的部分

错误:连接ECONNREFUSED 127.0.0.1:3306

127.0.0.1是引用用于访问它的当前计算机的主机名。

这意味着您正在尝试连接到运行NodeJS应用程序的同一台计算机上托管的数据库。但是Heroku dynos上没有安装MySQL。

要修复此问题,您需要转到Heroku应用的仪表板

  1. 转到Dashboard-> <您的应用>->设置->配置变量

  2. 点击Reveal Config Vars

  3. 使用适当的值填充环境变量(DB_URL,DB_NAME ...)

PS:您需要在某个地方托管一个MySQL数据库,AFAIK Heroku不提供MySQL数据库,但它们确实提供了Postgres

因此,您需要更改为Postgres或找到MySQL提供程序。