Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

req.body undefined and express api testing using angular

I am practicing API and having a small issue. Can someone please have a look the code below and let me know why req.body logs undefined when I do POST request using angular $http on the client side? also try a simple jquery AJAX request to have the same result.

//------------------  back-end
var express = require('express');
var mongoose = require('mongoose');
var app = express();

//connect DB
var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/Ecomm_db';
mongoose.connect(mongoURI);

//express config
app.use(express.static(__dirname + '/public'));

//DB setup
var Schema = mongoose.Schema;

var Product = new Schema({  
    title: { type: String, required: true },  
    description: { type: String, required: true },  
    style: { type: String, unique: true },  
    modified: { type: Date, default: Date.now }
});

var ProductModel = mongoose.model('Product', Product); 


//API
app.post('/api/products', function (req, res){
  var product;
  console.log("POST: ");
  console.log(req.body);
  product = new ProductModel({
    title: req.body.title,
    description: req.body.description,
    style: req.body.style,
  });
  product.save(function (err) {
    if (!err) {
      return console.log("created");
    } else {
      return console.log(err);
    }
  });
  return res.send(product);
});

//--------------------------- client-end
$http({
      method: 'POST',
      url: '/api/products',
      data: {
        title: "my t-shirts",
        description: "super good",
        style: "my style"
      }
    }).then(function (response){
      console.log('POST response',response);
    }, function (err){
      console.log('err:', err);
    })
like image 881
jhlosin Avatar asked Oct 27 '25 10:10

jhlosin


1 Answers

Try to use module 'body-parser'

var bodyParser = require('body-parser'); ... app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json());

like image 79
Helen Avatar answered Oct 29 '25 23:10

Helen