代码示例 -
const express=require('express'),
http=require('http'),
handlebars=require('express-handlebars').create({defaultLayout:'main'}),
fs=require('fs'),
mongoose=require('mongoose'),
uriUtil = require('mongodb-uri'),
credentials=require('./credentials.js'),
bodyParser=require('body-parser');
//connect to databse
var mongooptions = {
server: {
poolSize:5,
socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } },
replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 }
},
};
var mongodbUri=("mongodb://user:pwd@ds029831.mongolab.com:29831/project");
var mongooseUri=uriUtil.formatMongoose(mongodbUri);
mongoose.connect(mongooseUri,mongooptions);
var conn=mongoose.connection;
conn.on('error',function(err){
console.log(err.message);
});
conn.on('connection',function() {
var app=express();
app.set('port',process.env.PORT);
app.engine('handlebars',handlebars.engine);
app.set('view engine','handlebars');
app.use(express.static('./public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(require('express-session')({
secret: 'intro skill',
resave: false,
saveUninitialized: false,
cookie: {maxAge:900000}
}));
var userSchema=new mongoose.Schema({
username: String,
password: String,
email : String
});
var user=mongoose.model('users',userSchema);
//routing
function startServer(){
http.createServer(app).listen(app.get('port'),function(){
console.log("Server Started at port "+app.get('port'));
});
}
if(require.main===module){
startServer();
}
else{
module.exports=startServer;
}
});
这是我的node.js的代码。我正在使用mongolab作为mongodb
我在cloud9上运行app
当我使用mongoose连接到数据库时,由于无法连接到1%40ds029831.mongolab.com:29831 ,因此抛出错误。
应用程序正在连接到mongolab,并在身份验证(成功)后显示此错误。
请帮帮我。
答案 0 :(得分:3)
您的密码是否包含“@”字符?如果是,请将其替换为%40并再试一次,“@”字符应仅出现在主机名之前。