无法将表单数据提取到mongoDB

时间:2017-06-24 14:12:11

标签: javascript node.js mongodb express

这是我的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;

这是我的html文件,其格式为:

<!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>

我解决了req.body未定义的问题(替换了app.post和app.get for router.get和router.post)。但是,现在,错误消息是(当我填写表单并单击“提交”按钮时):

{"message":"Cannot read property 'get' of undefined","error":{}}

帮助我解决这个问题,我确信由于缺乏专业知识,这个错误很愚蠢。

P.S:这是我在package.json文件中的依赖项:

"dependencies": {
"body-parser": "~1.10.2",
"express": "~4.11.1",
"mongodb": "*",
"monk": "*",
"morgan": "*"
}

P.S.S:mongoDB已经建立并正在运行。

1 个答案:

答案 0 :(得分:1)

这是因为您将db定义为

var db = req.db;

那是未定义的

db是数据库的实例,只是注释该行,因为最初 已定义:

db = require("monk")("localhost:27017/nodemails"),

更多信息:

https://github.com/Automattic/monk