my code consists of server.js
file to create a node+ express server api. the server.js file consists of models that I have created and the routes with GET
, POST
methods.
server.js
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 cors = require('cors');
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 Contact = mongoose.model('Contact',{
name:String,
email:String,
number:Number,
address:String
});
//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');
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');
Then I have created my service class where I fetch my data from server. I don't have any problem in this.It is working absolutely fine.
Then comes my 2 pages where in the first page I create a contact list and in the second page I get that list from the server/db.
Please help me out that why am I not able to get the data from the db and post the correct data. The data that is posted in the db contains only Id and -v flag.
via Aditya Jain
No comments:
Post a Comment