我是 Node.js 的新手,我有一个使用 MySQL 数据库部署到 Heroku 的应用程序。
但是,我不断收到错误消息。该应用程序仅在我在 Heroku 上部署后才能运行一段时间。它突然停止工作,我收到以下错误:
events.js:160
throw er; // Unhandled 'error' event
Error: Connection lost: The server closed the connection.
at Protocol.end (/app/node_modules/mysql/lib/protocol/Protocol.js:113:13)
at Socket.<anonymous> (/app/node_modules/mysql/lib/Connection.js:109:28)
at emitNone (events.js:91:20)
at Socket.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickCallback (internal/process/next_tick.js:104:9)
State changed from up to crashed
Process exited with status 1
这是我的代码:
var express = require('express');
var app = express();
var mysql = require('mysql')
var bodyParser = require('body-parser');
const sortBy = require('sort-array')
app.set('port', (process.env.PORT || 5000));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));
var db_config = {
host: 'us-cdbr-iron-east-05.cleardb.net',
user: 'REDACTED',
password: 'REDACTED',
database: 'heroku_REDACTED'
};
var connection;
connection = mysql.createConnection(db_config);
var count2 = 10;
var count3 = 20;
var count4 = 10;
//SELECT COUNT(*) AS count2 FROM photos
app.get("/", function(req, res){
var q_users = "SELECT COUNT(*) AS count1 FROM users";
connection.query(q_users, function(err,results, fields){
if(err) throw err;
var count1 = results[0].count1;
//res.send(results);
res.render("home", {data1: count1, data2: count2, data3: count3,
data4: count4});
});
});
app.post('/adduser', function(req,res){
var person = { username: req.body.username};
connection.query('INSERT INTO users SET ?', person, function(err,
result){
if(err) throw err;
res.redirect("/");
});
});
app.post('/deleteuserid', function(req,res){
var id = req.body.userid;
connection.query('DELETE FROM users WHERE id = ?', id, function(err, result){
if(err) throw err;
//res.send(result);
res.redirect("/countpictures");
});
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
有人可以告诉我如何解决这个问题吗?我有很多 SQL 查询,并且我认为正在发生某种形式的超时。请告诉我应该进行哪些更改以避免此错误,以便我的应用程序稳定并且在每 5 分钟部署后不会崩溃。