隧道SSH无法在节点应用程序中成功连接到服务器

时间:2019-11-08 23:52:45

标签: node.js mongodb networking ssh-tunnel

我正在尝试连接到从本地计算机运行MongoDB的云服务器。我在正在创建的Node.js应用程序中使用tunnel-ssh,但是,我似乎有多个问题,而且我不完全了解发生了什么。

问题

  1. 我不确定100%是否成功连接到服务器。但是,当我console.log(server)_connections: 0,时没有错误。请参阅下面的完整日志。
  2. 如果我正在连接,然后尝试运行getDataFromMongoDB函数,它将返回错误EADDRINUSE:地址已在使用中127.0.0.1:27000。

我整天都在努力寻找解决办法,但是我什么也没得到。请帮忙。

错误1-服务器正在连接

Server {
  _events:
   [Object: null prototype] { connection: [Function], close: [Function] },
  _eventsCount: 2,
  _maxListeners: undefined,
  _connections: 0,
  _handle:
   TCP {
     reading: false,
     onread: null,
     onconnection: [Function: onconnection],
     [Symbol(owner)]: [Circular] },
  _usingWorkers: false,
  _workers: [],
  _unref: false,
  allowHalfOpen: false,
  pauseOnConnect: false,
  _connectionKey: '4:127.0.0.1:27017',
  [Symbol(asyncId)]: 7 }

代码

var config = {
  username: "root",
  Password: "password on the server",
  host: "server IP address",
  port: 22,
  dstHost: "127.0.0.1",
  dstPort: 27017,
  localHost: "127.0.0.1",
  localPort: 27000
};

var tnl = tunnel(config, function(error, tnl) {
  if (error) {
    console.log(error);
  }

  // yourClient.connect();
  // yourClient.disconnect();
  console.log(tnl);
  getDataFromMongoDB();
});

async function getDataFromMongoDB(page) {
  const MongoClient = require("mongodb").MongoClient;
  const uri = "mongodb://USRNAME:PASSWORD_FOR_MONGDB_DATABASE@localhost:27017";
  const client2 = new MongoClient(uri, { useNewUrlParser: true });
  const client = await connectToMongodb(client2);
  const collection = client.db("my_database_name").collection("jobs");
  const jobs = await collection.find().toArray();
  console.log("jobs", jobs);
}

function connectToMongodb(client) {
  return new Promise((resolve, reject) => {
    client.connect(function(err) {
      console.log("connected", err);
      return resolve(client);
    });
  });
}

0 个答案:

没有答案