我正在学习在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
我尝试了平台上的各种解决方案,但都没有成功。
我已经根据文档编写了代码,但仍然不知道是什么导致了错误。
谢谢您。
暂无答案!
目前还没有任何答案,快来回答吧!