【问题标题】:node.js app works locally but crashes when deployed on herokunode.js 应用程序在本地工作,但在部署在 heroku 上时崩溃
【发布时间】:2020-12-08 04:18:31
【问题描述】:

过去几天我一直在尝试在 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 能够毫无问题地加载我的主页,但是当我尝试访问其他页面(它们都从我的数据库加载和显示数据)时,它崩溃了。感谢大家的帮助!

【问题讨论】:

    标签: mysql node.js heroku npm


    【解决方案1】:

    这是错误中重要的部分

    错误:连接 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 提供程序。

    【讨论】:

    • 谢谢!这解决了我的问题并允许我访问所有其他页面而不会崩溃。
    【解决方案2】:

    错误消息指示“/app/routes/awards.routes.js”中的错误 在第 20 行 建立连接可能有问题 你能把它的代码放上去吗

    【讨论】:

      猜你喜欢
      • 2019-07-26
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 1970-01-01
      相关资源
      最近更新 更多