Wednesday, 10 May 2017

My `req.body` is passing undefined values so my db is not updating with the fields

My req.body gives me null value.How can I get the values so that I can store it in the db.So when I am refreshing the page the data gets away because the fields are not present in the db.

.js file

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var morgan = require('morgan');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var cors = require('cors');
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/contactlist');

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json());
app.use(bodyParser.json({type:'application/vnd.api+json'}));
app.use(methodOverride());
app.use(cors());


app.use(function(req,res,next){

    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Methods", "DELETE,PUT");
    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With, Content-Type, Accept");
    next();
});

var contactSchema = mongoose.Schema({
    name:String,
    email:String,
    number:Number,
    address:String
});

var Contact = mongoose.model("Contact", contactSchema);


//Routers
//get
app.get('/contacts',function(req,res){
    console.log('inside get router fetching the contacts');

    Contact.find(function(err, contacts){
        if(err)
        res.send(err);
        res.json(contacts);
    });

});

//post---->get

app.post('/contacts',function(req,res){
    console.log('creating the contacts');
    if(!req.body.name || !req.body.email || !req.body.number || !req.body.address){
        // res.render('show_message', {message: "Sorry, you provided worng info"});
        console.log('information not provided'); 
        console.log(req.body.name);  //undefined
         console.log(req.body.email); //undefined
          console.log(req.body.number); //undefined
    }
    else{

    Contact.create({
        name:req.body.name,    
        email:req.body.email,
        number:req.body.number,
        address:req.body.address,
        done: false
    },function(err,contact){
        if(err)
        res.send(err);

        Contact.find({},function(err,contact){
            if(err)
            res.send(err);
            res.json(contact);
        });
    });
    }
});

app.listen(8080);
console.log('App listening on port 8080');

Please hve a look in the comments where undefined is written.



via Aditya Jain

No comments:

Post a Comment