本人也是前端爱好者,最近在用Node.js和MongoDB搭建自己的网站,本地运行很好。
按照BAE上修改链接方式后,访问网站出错,提示:
可以访问 http://siblim.duapp.com/ 查看错误如下 Error: Error connecting to database: failed to connect to [127.0.0.1:27017] at null. (/home/bae/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/server.js:553:74) at EventEmitter.emit (events.js:106:17) at null. (/home/bae/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:140:15) at EventEmitter.emit (events.js:98:17) at Socket. (/home/bae/app/node_modules/connect-mongo/node_modules/mongodb/lib/mongodb/connection/connection.js:512:10) at Socket.EventEmitter.emit (events.js:95:17) at net.js:441:14 at process._tickCallback (node.js:415:13)
但是本地链接代码,个人已经修改了。怎么还会链接failed to connect to [127.0.0.1:27017]
//db.js 链接代码修改如下 var Db = require(‘mongodb’).Db; var Connection = require(‘mongodb’).Connection; var Server = require(‘mongodb’).Server; //数据库连接信息host,port,user,pwd var db_name = 'MOOEovYoNmLKlMCIfRdt’; // 数据库名,从云平台获取 var db_host = 'mongo.duapp.com’; // 数据库地址 var db_port = '8908’; // 数据库端口 var username = '。。。’; // 用户名(API KEY) var password = '。。。’; // 密码(Secret KEY)
module.exports = new Db(db_name, new Server(db_host, db_port, {}), {w: 1});
//post.js 调用代码如下 var mongodb = require(‘./db’); var moment = require(‘moment’);//时间模块 var formidable = require(“formidable”);//处理POST数据模块
function Post(username, post, target_path, time){ this.user = username; this.post = post; this.img = target_path; if (time) { this.time = time; }else{ this.time = new moment().format(“YYYY-MM-DD HH:mm:ss”); //console.log(moment().format()); }
}; module.exports = Post;
Post.prototype.save = function save(callback) {
// 存入 MongoDB的文档
var post = {
user: this.user,
post: this.post,
img: this.img,
time: this.time,
};
mongodb.open(function(err,db){
if(err) return callback(err);
//读取post集合
db.authenticate("。。。", "。。。", function(err, result) {
if (err) {
db.close();
console.log(err);
return;
}
db.collection('posts’,function(err, collection){
if (err) {
mongodb.close();
return callback(err);
};
//为user属性添加索引
collection.ensureIndex(‘user’);
//写入post文档
collection.insert(post, {safe: true}, function(err, post){
mongodb.close();
callback(err, post);
});
});
});
});
};
Post.get = function get(username, callback){
mongodb.open(function(err, db){
if (err) {return callback(err)};
db.authenticate("。。。", "。。。", function(err, result) {
if (err) {
db.close();
console.log(err);
return;
}
db.collection('posts’, function(err, collection){
if(err) {
mongodb.close();
return callback(err);
};
//查找user属性为username的文档,如果username是null则匹配全部
var query = {};
if (username) {
query.user = username;
};
collection.find(query).sort({time: -1}).limit(30).toArray(function(err, docs){
mongodb.close();
if(err) {
callback(err,null);
};
//封装posts为post对象
var posts = [];
docs.forEach(function(doc, index){
var post = new Post(doc.user, doc.post, doc.img,doc.time);
posts.push(post);
});
callback(null,posts);
});
});
});
});
}