My objective is to simply insert a message into database from a form post.
I have tried the following code without using any framework.
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}/`);
});
Now after running and submitting a form post although the document get inserted but i get error "the options [servers] is not supported the options [caseTranslate] is not supported" in console. Please assist me what is the proper way to achieve the goal or any workaround. Thanks.