BodyParser doesn't recognise input

732 views Asked by At

i'm trying to implement a login page using express and body parser, my code is as follows:

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);

The problem is, when I send the info (name and password), the console displays: { name: undefined, password: undefined } But when I use the line console.log(req), the console does show all the request info (which is supposed to be converted into name and password by body-parser).

How do I solve this undefined issue? Thanks in advance.

2

There are 2 answers

0
Bidhan On

You're trying to parse multipart data(enctype="multipart/form-data") using body-parser. You cannot do that. It is written in the documentation too. Use connect-multiparty module if you want to parse multipart form data.

0
asantiagot On

I managed to make it work using this code

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');

I still don't know how, but it works.