I was trying to input Text data to a MongoDB database using just a HTML form. But when I ran it locally it doesn't work. I think this had something to do with creating a Node.js server. But I can't figure out how to run a HTML file (which is index.html
here). I have only learned to run just the JavaScript code alone in the Node console. I don't know how I can run this index.html locally on NodeJS.
Also I want to do this without using ExpressJS! Everything I found online showed only on how to do this using ExpressJS. Is there a reason behind it? Can't we able to do this using just NodeJS and MongoDB? (LOCALLY on Windows)
var MongoClient = require("mongodb").MongoClient;
var url = "mongodb://localhost:27017";
function addData(){
var record = document.getElementById("title").value;
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("notetest");
var record2value = { title: record };
dbo.collection("page1").insertOne(record2value, function (err, res) {
if (err) throw err;
console.log("1 document added!");
db.close();
})
})
};
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type="text/javascript" src="scripts/script.js"></script>
</head>
<body>
<form onsubmit="addData()">
<input type="text" name="title" id="title">
<input type="submit" name="submit" id="submit">
</form>
</body>
</html>
UPDATE: Also I tried calling this index.html
using Node. By using the following code.
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
But I don't know why I am not seeing the console.log
from MongoDB, which should say "1 document added!".