Connect MySQL database with node JavaScript application

ε祈祈猫儿з 提交于 2020-04-30 06:26:21

问题


I make a node JavaScript app and deploy it on cPanel using SSH. App is working fine without database but when I connect the app with database on cPanel (GoDaddy) it takes times and shows the message "Error establishing a database connection". My connection code

const mysql = require('mysql');
const express = require('express');
const app = express();

var pool = mysql.createConnection({
    host: 'localhost',
    user: '<MY_USER_NAME>',
    password: '<MY_PASSWORD>',
    database: '<DB_NAME>'
});

pool.connect(function(err) {
  if (err) throw err;
  else{
  console.log("Connected!");
  }
});



module.exports = pool;

route where DB interact,but lost the connection.

app.post('/loginn', (req, res) => {
var id = req.body.id
  console.log("user_id= "+id);
  var sql = "select * from users where id  NOT IN ('" + id + "') ";
    pool.query(sql, function (err, rows) {
        if (err) throw err;
        else {
          res.render('allusers', {
            users: rows,
            user_id:id
          })
        }
    });
  });

回答1:


This answer is going to take the form of a debugging journey, because that's the only way I can see to get to the bottom of your issue.

Let's do a dead-simple representation of your app to make sure that you can send a query to MySQL and receive a response from a route-handler in Express. Setup your app like this:

const mysql = require('mysql');
const express = require('express');
const app = express();
const PORT = // define the PORT for your host

var connection = mysql.createConnection({
    host: 'localhost',
    user: '<MY_USER_NAME>',
    password: '<MY_PASSWORD>',
    database: '<DB_NAME>'
});

connection.connect(function(err) {
  if (err) console.error(err);
  console.log("Connected!");
});

app.get('/db-test', (req, res, next) => {

  var id = // fill in a user_id that you know exists
  var sql = `SELECT * FROM users WHERE id NOT IN ('${id}') `;

  console.log(sql); // confirm you are sending the sql request you believe you should be sending

  connection.query(sql, function (err, results, fields) {
      if (err) console.error(err);
      console.log(`results: ${results}\nfields: ${fields}`);
  });

});

app.listen(PORT);

And then hit the route /db-test from your app, and see what happens. If this works, then we will have at least proved that you CAN make requests between Express and MySQL. Right now, I'm not sure you can, so I'm not sure what to debug.



来源:https://stackoverflow.com/questions/60906248/connect-mysql-database-with-node-javascript-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!