我正在使用Cloude 9环境开发我的nodejs应用程序。在那里我编写了连接到mongodb数据库的代码。我成功连接到数据库。但是,当我尝试对数据库进行操作时,页面变得无法响应并挂起。
以下是我的server.js文件的代码
class unicode_replace_entities {
public function UTF8entities($content="") {
$contents = $this->unicode_string_to_array($content);
$swap = "";
$iCount = count($contents);
foreach ($contents as $k=>$v) {
$contents[$k] = $this->unicode_entity_replace($v);
$swap .= $contents[$k];
}
return mb_convert_encoding($swap,"UTF-8");
}
请注意,在我的视图页面中,我使用POST方法调用操作var Db = require('mongodb').Db;
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var ejs = require('ejs');
var app = express();
var helpers = require('express-helpers')
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
var db;
helpers(app);
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded
var server = http.Server(app);
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () {
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/public/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//app.use(express.static(__dirname + '/client'));
app.use(express.static(path.join(__dirname, '/client')));
// MongoDB Connection
app.use(function(req, res, next) {
next();
})
app.post('/ajax-mongo-connect', function (req, res) {
var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
if(err){
console.log(err);
}else{
var db = mongoClient.db("mydb");
console.log('database connected',db);
mongoClient.close();
}
})
})
。要打电话到ajax-mongo-connect
,但是页面变得不负责任并挂起。
让我知道我在做什么。
答案 0 :(得分:0)
您需要在/ajax-mongo-connect
路线中退回某些内容,例如res.send('its working dude!');
或致电next()
功能。
干杯!