Reputation:
I have written a small code in node.js to insert a document in MongoDB collection. But as I make a request for profile route I get the error I mentioned in the title. I can't figure out which line is causing the problem, maybe it is the one after insertOne method. The code is:
http
.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/html" });
var url = req.url;
if (url == "/") {
res.end("<h1>Basic route</h1>");
} else if (url == "/profile") {
mydb
.collection("record")
.insertOne({ username: "vipul", password: "vipul1234" }, (err, result) => {
if (err) res.end(err);
else res.end("inserted successfully");
});
} else if (url == "/about") {
res.end("<h1>About Us Page</h1>");
} else {
let date = Date();
res.end("<h1>Incorrect URL</h1><h2>", date, "</h2>");
}
})
.listen(3000, () => {
console.log("Server listening at port 3000");
});
Please guide me through. I am a beginner to Node!
Upvotes: 0
Views: 131
Reputation: 2684
About this:
if (err)
res.end(err);
else
res.end("inserted successfully");
res.end
does not accept the error itself. You have to pass it a string or a buffer.
(See more here: https://nodejs.org/api/http.html#http_response_end_data_encoding_callback)
You can try this:
if (err)
res.end(err.message);
else
res.end("inserted successfully");
Upvotes: 1