我的目标是简单地从表单发布中向数据库中插入一条消息。
我没有使用任何框架就尝试了以下代码。
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 = "";
client.connect(err => {
const collection = client.db("mydb").collection("messages");
console.log('Connected successfully to database server');
collection.find({}).toArray(function (err, docs) {
messages += "<table border='1'><tr><th>Messages</th></tr>"
for (var x in docs) {
messages += "<tr><td>" + docs[x].message + "</td></tr>";
}
messages += "</table>"
});
});
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.write(`
<!doctype html>
<html>
<body>
${messages}
<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");
})
});
});
res.end();
}
res.end();
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
现在在运行并提交表单后,尽管插入了文档,但出现错误“不支持选项[服务器] 控制台中不支持[caseTranslate]选项。请协助我实现目标或任何解决方法的正确方法是什么。