3gwebtrain 3gwebtrain - 5 months ago 20
Node.js Question

`express` app - not able to test the `post` request using `postman`

I have created a small

express
app. I just trying to test the
post
method. But it's not working at all. according to me all are fine. But I couln't figure out the issue. any one help me here please?

my server.js file :

var express = require('express');
var bodyParser = require('body-parser');
var Post = require('./models/post');

var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));

app.use(bodyParser.json());

app.get('/api/posts', function( req, res) {
res.json([
{
username:"dickeyxxx",
body : "node rocksxx"
}
])
});


app.post('/api/posts', function( req, res, next) {

var post = new Post({
username:req.body.username,
body:req.body.body
})

post.save(function(err, post){
if(err) { return next }
res.json(201,post);
})

})



app.listen(5000, function(){
console.log('Server Listening on', 5000);
})


my post.js :

var db = require('../db');
var Post = db.model('Post', {
username:{type:String, required:true},
body:{type:String,required:true},
date:{type:Date, required:true,default:Date.now}
});

module.exports = Post;


my db.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/social', function(){
console.log( 'mongoose connected' ); //i am getting consoled
});

module.exports = mongoose;


my try with postman :

postman screen shot

any one help me here?

Answer

Your res.json(201,post); is wrong.

If you want to send status 201 then use

res.status(201).json(post);

see http://expressjs.com/en/api.html#res.json