我的目标是简单地从表单发布中向数据库中插入一条消息。
我没有使用任何框架就尝试了以下代码。
const http = require('http');
const MongoClient = require('mongodb').MongoClient;
var qs = require('querystring');
var url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const uri = 'mongodb://localhost:27017';
const client = new MongoClient(uri, { useNewUrlParser: true });
var messages = "";
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(`
<!doctype html>
<html>
<body>
<form action="/" method="post">
<input type="text" name="message" />
<button>Insert</button>
</form>
</body>
</html>);
if (req.method === 'POST') {
var body = '';
req.on('data', function (data) {
body += data;
});
req.on('end', function () {
var post = qs.parse(body);
client.connect(err => {
const collection = client.db("mydb").collection("messages");
collection.insertOne(post, function(err, res) {
if(err) throw err;
console.log("1 document inserted");
client.close(); // Either I place it here or don't close the connection at all still showing error
})
});
});
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
现在,当我运行该应用程序时,它会不断加载/请求,并在提交消息后引发抛出错误“ MongoError:服务器实例池已损坏”。请协助我实现目标或任何解决方法的正确方法是什么。谢谢。