0

I cannot seem to POST data via Postman & Express. My POST verb code is as follows

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

var fdbRouter = express.Router();
fdbRouter.route('/films')
//post verb
.post(function (req, res) { 

var item = new Film(req.body);
console.log(item);
//item.save();
res.status(201).send(item);

})

And my Postman setup is as follows

postman setup

I have befriended google and came up with this 1. Node.js/Express form post req.body not working 2. req.body empty on posts 3. Express + Postman, req.body is empty 4. `express` app - not able to test the `post` request using `postman`

PS The watched item in postman is default in the mongoose schema i have so it's created regardless whether express works or not.

Community
  • 1
  • 1
EL Taipan
  • 51
  • 7

1 Answers1

0

Whenever I have worked with a post request in express it's been formatted as below (assuming you're using mongoDB):

var express = require('express');
var fdbRouter = express.Router();
var model = require("<FILE TO IMPORT MODEL>") //This file will differ, but you need to import the model you created for films in your DB
var FilmModel = model.Film //also depends on how you exported your model in your dbFiles. Either way you need this model as the blue print for your post request

//I'm also assuming here that you're calling /films correctly and have it sourced as such in your app.js so you don't need /api/films as you have listed in your postman setup image 

fdbRouter.post('/films', function(req,res){
  var newfilm = new FilmModel()
  newFilm.title = req.body.Title
  newFilm.year =  req.body.Year
  newFilm.genre = req.body.Genre
  newFilm.save(function(err, savedObject){
    if(err){
      console.log(err)
      res.status(500).send()
    }else{
      res.send(savedObject)
    }
  })
})

Please note: this code example assumes a test db with a schema and model has been setup and is available for import to your routes file.

Let me know if this puts you on the right track!

  • I have tried it. It still doesn't work. Same response as the one in postman. ps. There's no '/films' route its '/api/films'. – EL Taipan Sep 20 '16 at 14:49
  • I found the culprit. It turns out the letter cases in the schema were different from the one in the DB. ie the one in the DB were caps and the one in the model were small caps. Thanks! – EL Taipan Sep 21 '16 at 22:00