Reputation: 89
Here is my app.js:
var express = require("express"),
mongo = require("mongodb"),
db = require("monk")("localhost:27017/nodemails"),
bodyParser = require("body-parser"),
logger = require("morgan"),
path = require("path");
var app = express();
var router = express.Router();
var port = 3000;
app.use(router);
app.use(express.static(__dirname, "public"));
app.use(logger("dev"));
router.use(bodyParser.urlencoded({extended: true}));
router.use(bodyParser.json());
// Connect my DB here
app.use(function (req,res,next) {
req.db = db;
next();
});
// Catch 404 error
app.use(function (req,res,next) {
var err = new Error("Not found");
err.status = 404;
next(err);
});
// Development error handler
if (app.get("env") === "development") {
app.use(function (err,req,res,next) {
res.status(err.status || 500);
res.json({
message: err.message,
error: err
});
});
}
// Production error handler: no stacktraces
app.use(function (err,req,res,next) {
res.status (err.status || 500);
res.json({
message: err.message,
error : {}
});
});
router.all("/", function (req,res,next) {
console.log("Visit registered");
next();
});
// Join homepage
router.get("/", function (req,res) {
res.sendFile(path.join(__dirname, "public", "collection.html"));
});
// Upload email to DB
router.post("/addMail", function (req,res) {
var db = req.db;
var userEmail = req.body.useremail;
console.log(req.body.useremail);
var collection = db.get("usercollection");
collection.insert({"email": userEmail}, function (err,doc) {
if (err) {
res.send("Somehow it is error, bruh");
} else {
res.redirect(__dirname, "public", "/thankyou.html");
}
});
});
app.listen(port);
module.exports = app;
Here is my html file with form:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="mailForm" action="/addMail" method="post">
<div>
<label for="useremail">Email: </label>
<input type="text" id="useremail" name="useremail"> </input>
</div>
<input type="submit" value="Submit"> </input>
</form>
</body>
</html>
I solved the problem with the req.body being undefined (replaced app.post and app.get for router.get and router.post). However, now, the error message is (when I fill in the form and click submit button):
{"message":"Cannot read property 'get' of undefined","error":{}}
Help me out with this, I am sure that the mistake is silly due to my lack of expertise.
P.S: Here are my dependencies in package.json file:
"dependencies": {
"body-parser": "~1.10.2",
"express": "~4.11.1",
"mongodb": "*",
"monk": "*",
"morgan": "*"
}
P.S.S: the mongoDB is already set up and working.
Upvotes: 1
Views: 78
Reputation: 1138
That is because your are defining db
as
var db = req.db;
and that is undefined
db
is you instance of database, only comment that line, because initially
already is defined:
db = require("monk")("localhost:27017/nodemails"),
More information:
https://github.com/Automattic/monk
Upvotes: 1