我正在尝试使用 express 和 body 解析器实现登录页面,我的代码如下:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost/database", function(err){
if(err) throw err;
console.log("DB Connection was successful");
});
var Schema = mongoose.Schema;
var userSchema = mongoose.Schema({
name: {type: String, required: true, index: {unique: true}},
password: {type: String, required: true}
});
var user = mongoose.model("user", userSchema);
app.set("view engine","jade");
app.use(express.static("public"));
app.get('/',function(req,res){
res.render("index");
});
console.log('Service has started');
app.post("/menu", function(req, res){
console.log(req);
var data = {
name: req.body.name,
password: req.body.password
}
console.log(data); //I'm trying to display the user received in the login
res.render("auth");
});
app.listen(8080);
问题是,当我发送信息(名称和密码)时,控制台显示:{ name: undefined, password: undefined }
但是当我使用 lineconsole.log(req)
时,控制台确实显示了所有请求信息(应该由 body-parser 转换为名称和密码) .
我该如何解决这个undefined
问题?提前致谢。