I want to have a server running to make some entries in a database. I havent done that before. Im using node.js, express for the server and mysql with node-mysql and host it on uberspace as a low-cost webhosting service. When im starting the server with 'nohup node app.js &' everything seems to work fine, but after some time, I dont get any response from the server in a webbrowser anymore. I think the server just hang up and I want to restart it automatically. Here the simple code for my app.js:
var express = require('express');
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '***',
database: '***',
user : '***',
password: '***',
port: 3306
});
connection.connect(function(err) {
console.log(err);
});
app.get('/test', function(req,res) {
var post = {ID: 1, User: "testuser"};
var query = connection.query('INSERT INTO testtabelle123 SET ?', post, function(err, results){
console.log(err);
});
console.log(query.sql);
res.send(query.sql);
});
I guess I simply just have to make a little change for automatically restart in the code and maybe use some sort of middleware/tool for that. Can you tell me what to do? Havent found simple solutions on SO so far.
Problem occurs because mysql is closing connection when there is no connection (after sometime). Add this to make connection alive forever:
setInterval(function () {
connection.query('SELECT 1', [], function () {})
}, 5000)
Relevant issue: https://github.com/felixge/node-mysql/issues/1337