从Node-JS服务器连接到MySQL时出错

时间:2018-06-14 19:39:55

标签: mysql node.js ubuntu-server

我正在学习在node-js上开发服务器并开发了一个基本的get函数,它从在digitalocean上的ubuntu服务器上托管的MySQL数据库中检索数据。

这是我的代码:

const express = require('express')
const app = express()
const mysql = require('mysql')
const Client = require('ssh2').Client;
const ssh = new Client();

const db = new Promise(function(resolve, reject){
ssh.on('ready', function() {
  ssh.forwardOut(
    // source address, this can usually be any valid address
    'localhost',
    // source port, this can be any valid port number
    3333,
    // destination address (localhost here refers to the SSH server)
    'xxx.xxx.xxx.xxx',
    // destination port
    22,
    function (err, stream) {
      if (err) throw err; // SSH error: can also send error in promise ex. 
reject(err)
      // use `sql` connection as usual
         connection = mysql.createConnection({
          host     : '127.0.0.1',
          user     : 'user',
          password : 'pass', 
          database: 'mysql',
          stream: stream
        });

        // send connection back in variable depending on success or not
    connection.connect(function(err){
        if (!err) {
            resolve(connection)
        } else {
            reject(err)
        }
    });
  });
}).connect({
  host: 'xxx.xxx.xxx.xxx', //IP address where DB is hosted
  port: 22,               //Port refering to the IP 
  username: 'user',       //username to loginto the host  
  password: 'pass'  //password to log into host
});
});

//Retrieve route
app.get('/users', (req, res) => {
//console.log("Fetching user with id: " + req.params.id)

const queryString = "SELECT * FROM user"

connection.query(queryString, (err, rows, fields) => {

if(err){
    console.log("Failed to query " + err)
    res.sendStatus(500)
    return
}
console.log("Fetch Succesful")
res.json(rows)
})
})


app.listen(3000, () => {
console.log("Server is up and listerning on port 3000")
})

当我在本地计算机上运行此代码时,它能够连接到外部数据库并获取数据。我在digitalocean上创建了另一个服务器并托管了相同的代码。但是在运行它时,我在连接时遇到错误:UnhandledPromiseRejectionWarning: Error: connect ECONNREFUSED 127.0.0.1:3306 我尝试了平台上提供的各种解决方案,但无法提升。

我已经编写了符合文档的代码,但仍然无法解释导致错误的原因。

谢谢。

0 个答案:

没有答案