BodyParser不识别输入

时间:2015-06-12 17:36:30

标签: node.js express body-parser

我尝试使用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 }但是当我使用行console.log(req)时,控制台会显示所有请求信息(这是应该通过body-parser转换为名称和密码。)

如何解决此undefined问题?提前谢谢。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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');

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