Reputation: 1374
I have my angularjs code which tries to send a post request as follows
var req = {
method: 'POST',
url: 'http://localhost:3300/addInventoryItem',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
item_name : item.itemName
}
};
$http(req).then(function(response){...});
I have my nodejs express code to have this
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post("/addInventoryItem", function(req, res) {
console.log(req.body);
});
I always get the request in my node as
{ '{"item_name":"sweetB"}': '' }
Why is the req.body
have the key as the entire form data as key? How can I solve this?
EDIT I am using express with body-parser module
Thanks for your help
Upvotes: 2
Views: 187
Reputation: 634
Try sending data in encoded format with request headers as json.
var data = $.param({
json: JSON.stringify({
item_name : item.itemName
})
});
Upvotes: 2
Reputation: 4565
As mentioned by @mzulch in comments, you're looking for a body parser, so that Express would parse the request body for you.
var app = express();
//...
var bodyParser = require('body-parser');
// parse urlencoded request body
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb'}));
Then, in controller, you'll have an object:
app.post("/addInventoryItem", function(req, res) {
// req.body is an object: {"item_name":"sweetB","item_price":10}
console.log(req.body);
});
Upvotes: 1