0

I need help on this one I'm stuck for three days... I need to deploy a node.js web app with MySql database to Heroku. Here what I`m done so far:

  • I succeeded to connect to heroku local on port 5000;
  • I succeeded to connect with the command heroku run node app.js;
  • I insert a proc file on the root directory :

Please help!

web: node app.js

But when I open the app from the heroku web site I have the following errors:

enter image description here

Here is my server file :

const express = require("express");
const exphbs = require("express-handlebars");
const bodyParser = require('body-parser');
const mysql = require('mysql');

require("dotenv").config();

const app = express();
const port = process.env.PORT || 5000;

// Parsing middleware
// Parse application/x-www-form-urlcoded
app.use(express.urlencoded({extended: true})); //New
app.use(express.json()); //To parse the incoming requests with JSON payloads

//to load static file
app.use(express.static("public"));

//Templating engine to change the extenion of file from .handlebar to .hbs
app.engine("hbs", exphbs({extname:".hbs"}));
app.set("view engine","hbs");


   

//Routes
const routes = require('./server/routes/user');
app.use("/",routes);

//Listen on port 5000
app.listen(port, () => console.log(`Listening on port ${port}`));

Here my app.js file

const mysql = require('mysql');

//Connection pool
let connection = mysql.createConnection({
    host: process.env.DB_HOST,
    user: process.env.DB_USER,
    password: process.env.DB_PASS,
    database: process.env.DB_NAME
});



// View Users
exports.view = (req, res) => {
    //User the connection
    connection.query('SELECT * FROM user WHERE status="active"', (err, rows) => {
        //when done with the connection, release it
        if (!err) {
            let removedUser = req.query.removed;
            res.render('home', { rows, removedUser });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);
    });
};


//find user by Search
exports.find = (req, res) => {
    let searchTerm = req.body.search;
    //User the connection
    connection.query('SELECT * FROM user WHERE first_name LIKE ? OR last_name LIKE ?', ['%' + searchTerm + '%', '%' + searchTerm + '%'], (err, rows) => {
        if (!err) {
            res.render('home', { rows });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);
    });
};

exports.form = (req, res) => {
    res.render('add-crew');
}

   
exports.create = (req, res) => {
    const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;
    let searchTerm = req.body.search;

    //User the connection
    connection.query('INSERT INTO user SET first_name = ?,last_name = ?,email = ?,phone = ?,coc=?,expiration=?,PSSR=?,FFB=?,ADV=?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV], (err, rows) => {
        if (!err) {
            res.render('add-crew', { alert: 'Crew member added succesfully!' });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);

    });

};
// edit crew function
exports.edit = (req, res) => {
    //User the connection
    connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
        if (!err) {
            res.render('edit-crew', { rows });
        } else {
            console.log(err);
        }
        console.log('The data from uer table:\n', rows);
    });
}
// Update crew
exports.update = (req, res) => {
    const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;

    connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, PSSR=?, FFB=?, ADV=? WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV,  req.params.id], (err, rows) => {
        if (!err) {
            connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
                //when done with the connection release it
                // connection.release();
                if (!err) {
                    res.render('edit-crew', { rows, alert: `${first_name} has been updated.` });
                } else {
                    console.log(err);
                }
                console.log('The data from user table:\n', rows);
            });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);
    });
}


//delete crew
exports.delete = (req, res) => {
    // User the connection
    connection.query('DELETE FROM user WHERE id = ?', [req.params.id], (err, rows) => {
          if(!err) {
            let removedUser = encodeURIComponent();
            res.redirect('/?removed='+ removedUser);
          } else {
            console.log(err);
          }
          console.log('The data from user table: \n', rows);
      
        });
}
  
    
// hide user
    // connection.query('UPDATE user SET status = ? WHERE id = ?', ['removed', req.params.id], (err, rows) => {
    //     if (!err) {
    //       let removedUser = encodeURIComponent('User successeflly removed.');
    //       res.redirect('/?removed=' + removedUser);
    //     } else {
    //       console.log(err);
    //     }
    //     console.log('The data from beer table are: \n', rows);
    //   });
    
    // }



exports.viewall = (req, res) => {
    //User the connection
    connection.query('SELECT * FROM user WHERE id=?',[req.params.id], (err, rows) => {
        //when done with the connection, release it
        if (!err) {
            res.render('view-crew', { rows });
        } else {
            console.log(err);
        }
        console.log('The data from user table:\n', rows);
    });
}

Here my package.json file:

{
  "name": "nodejs-usermanagement",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "dotenv": "^10.0.0",
    "express": "^4.17.1",
    "express-handlebars": "^5.3.2",
    "mysql": "^2.18.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

Here an update about the errors that are coming out after 10 minutes:

enter image description here

  • You have to obtain the database url from *env*. Heroku provides you the connection parameters in a single env called: **CLEARDB_DATABASE_URL** and not splitted between user, db, etc... See [this](https://devcenter.heroku.com/articles/cleardb) for more information. – Carlo Corradini Jun 23 '21 at 17:16
  • 1
    See [connection options](https://github.com/mysqljs/mysql#connection-options) from *mysqljs*. You can pass the string URL directly when calling ```mysql.createConnection(process.env.CLEARDB_DATABASE_URL)``` – Carlo Corradini Jun 23 '21 at 17:19
  • Hi Carlo, I will pass the string directly then. I will let you know how is going... – Cesare Mannino Jun 23 '21 at 17:26
  • Carlo it worked. I really thank you a lot!!!. If you are on Twitter I would like to follow you. I was stuck since three days.... – Cesare Mannino Jun 23 '21 at 17:34
  • Ahahah I'm glad that we solved it! No problem for twitter. If you want (see more projects with Node.js | Typescript | GraphQL | TypeORM) here is my GitHub profile: [https://github.com/carlocorradini](https://github.com/carlocorradini) – Carlo Corradini Jun 23 '21 at 17:50
  • Carlo, after 10 minutes the app crash again, We are connected on gihub now the app is called vms, please have a look – Cesare Mannino Jun 23 '21 at 18:21
  • Update the question with the error – Carlo Corradini Jun 23 '21 at 18:31
  • For some reason I can`t edit it. – Cesare Mannino Jun 23 '21 at 18:49
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/234126/discussion-between-cesare-mannino-and-carlo-corradini). – Cesare Mannino Jun 23 '21 at 18:59
  • I found out the issue is solved here: https://stackoverflow.com/questions/58034107/why-does-my-node-app-works-for-a-few-moments-on-and-crashes-heroku – Cesare Mannino Jun 24 '21 at 19:08

0 Answers0