0

我正在尝试使用 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问题?提前致谢。

4

2 回答 2

1

您正在尝试enctype="multipart/form-data"使用 body-parser 解析多部分数据()。你不能这样做。它也写在文档中。如果要解析多部分表单数据,请使用connect-multiparty模块。

于 2015-06-12T18:07:30.493 回答
0

我设法使用此代码使其工作

var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var app = express();

mongoose.connect("mongodb://localhost/database");
var userSchema = {
    name: String,
    pass: Number
};

var User = mongoose.model("User",userSchema);

app.use(express.static("public"));
app.set("view engine","jade");
app.get('/',function(req,res){
    res.render("index");
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));


app.post("/auth",function(req,res){

    console.log(req.bodyParser);
    var data={name:req.body.name,
                pass:req.body.pass};
    console.log(data);
    res.render("index");
});    

app.listen(8080);
console.log('Service started');

我仍然不知道如何,但它有效。

于 2015-06-12T18:18:42.937 回答