when creating object post request, both of fields come request body being set field name itself. not getting errors not getting expected json object of request body in response. using local mongodb instance using mongolab database, thought maybe solve problem nothing changed.
var express = require("express"); var router = express.router(); var post = require("../app/models/post.js"); /* //drop post collection post.remove({}, function(err, num_docs) { if (err) { res.send(err); } else { console.log("collection dropped, documents deleted: " + num_docs); } }); */ // middleware routes. router.use(function(req, res, next) { console.log("api request made."); next(); // go next routes, don't stop here }); // test route ensure routing working router.get("/", function(req, res) { res.json({ message: "hooray! welcome api!" }); }); // on routes end in /posts router.route("/posts") // create post. (accessed @ post http://localhost/api/posts) .post(function(req, res) { var post = new post(); // create new instance of post model if (req.body.title !== undefined) { post.title = req.body.title; // set title (from request) } if (req.body.content !== undefined) { post.content = req.body.content; // set content (from request) } // save post, , check errors. post.save(function(err) { if (err) { res.send(err); } else { res.json(req.body); } }); }) .get(function(req, res) { post.find({}, { "__v": 0, "_id": 0 }).exec(function(err, posts) { if(err) { res.send(err); } else { res.json(posts); } }); }); module.exports = router;
request json:
{ "title": "sample title", "content": "sample content" }
output:
[ { "lastupdated": "2016-01-29t07:26:01.810z", "uploaddate": "2016-01-29t07:26:01.810z", "content": "content", "title": "title" } ]
you can't use req.body without including body parser , expect req.body produce expected result in express. did npm install body-parser
. don't see requiring body-parser
in code. maybe included body-parser in main file. believe if don't use req.body empty.
add below other requires
var bodyparser = require("body-parser");
app.use(bodyparser.urlencoded({extended : false}));
app.use(bodyparser.json())
and don't forget npm install body-parser
in terminal.
Comments
Post a Comment