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);
})
Try to use module 'body-parser'
var bodyParser = require('body-parser');
...
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With