0

node.js通过本地连接可以连接至服务器,

js代码:

var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://user:123456@localhost:27017/test”;

MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(“test”);
var myobj = { name: “菜鸟教程”, url: “www.runoob” };
dbo.collection(“sites”).insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(“文档插入成功”);
db.close();
});
});

服务器响应:

{“t”:{“$date”:”2021-05-20T17:25:53.519+08:00″},”s”:”I”, “c”:”NETWORK”, “id”:22943, “ctx”:”listener”,”msg”:”Connection accepted”,”attr”:{“remote”:”127.0.0.1:49845″,”connectionId”:2,”connectionCount”:1}}
{“t”:{“$date”:”2021-05-20T17:25:53.544+08:00″},”s”:”I”, “c”:”NETWORK”, “id”:51800, “ctx”:”conn2″,”msg”:”client metadata”,”attr”:{“remote”:”127.0.0.1:49845″,”client”:”conn2″,”doc”:{“driver”:{“name”:”nodejs”,”version”:”3.6.7″},”os”:{“type”:”Windows_NT”,”name”:”win32″,”architecture”:”x64″,”version”:”10.0.17763″},”platform”:”‘Node.js v14.16.1, LE (legacy)”}}}
{“t”:{“$date”:”2021-05-20T17:25:53.622+08:00″},”s”:”I”, “c”:”ACCESS”, “id”:20250, “ctx”:”conn2″,”msg”:”Authentication succeeded”,”attr”:{“mechanism”:”SCRAM-SHA-256″,”speculative”:true,”principalName”:”user”,”authenticationDatabase”:”test”,”remote”:”127.0.0.1:49845″,”extraInfo”:{}}}
{“t”:{“$date”:”2021-05-20T17:25:53.719+08:00″},”s”:”I”, “c”:”NETWORK”, “id”:22944, “ctx”:”conn2″,”msg”:”Connection ended”,”attr”:{“remote”:”127.0.0.1:49845″,”connectionId”:2,”connectionCount”:0}}

但如果将url改为具体的IP地址,var url = “mongodb://user:123456@120.80.105.24:27017/test”,

node返回error:

MongoNetworkError: failed to connect to server [120.80.105.24:27017] on first connect [Error: connect ECONNREFUSED 120.80.105.24:27017

服务器无响应。

备注:本人用的是阿里云服务器,,已将mongod.cfg的bindIp改为0.0.0.0,防火墙已关闭,已添加入站规则的端口27017。

发表新评论

首先确认本地IP地址是多少?
ifconfig或者ip a来获取地址,然后确认你的地址访问地址是否正确

其次检查配置来验证0.0.0.0是否生效或者通过os命令
db.runCommand(“getCmdLineOpts”);

netstat -anlp |grep 27017看下监听地址,是否0.0.0.0已经生效

最后可以通过命令行访问数据库是否可以访问
mongo “mongodb://user:123456@120.80.105.24:27017/test”