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

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

过去的几天,我一直在尝试在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,next) {
        mysql.pool.query("",[],rows2) => {
            mysql.pool.query("",rows) => {
                if (err) {
                    throw(err);
                } else {
                    let context = {
                        data: rows,data2: rows2
                    };
                    res.render('awards',context);
                }
            });
        });
    })
    .post(function (req,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 ()",result) {
                if (err) {
                    next(err);
                    return;
                }
                getAllAwardsData(res);
            });
        }
    })
    .delete(function (req,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,result) {
            if (err) {
                next(err);
                return;
            }
            context.results = "Updated row";
            res.send(context);
        });
    });

module.exports = router;

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

解决方法

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

,

这是错误中重要的部分

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-