2

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

Mani
  • 1,364
  • 14
  • 33
  • 1
    Have you already added middleware to parse `x-www-form-urlencoded` request bodies (https://github.com/expressjs/body-parser)? – mzulch Jan 13 '16 at 21:39
  • I don't understand, do you mean that another key-value is added to your data object? Because I don't see 'item_price' in the data that your are sending. – Loolooii Jan 13 '16 at 21:41
  • 1
    On second look I don't think angular will urlencode the data for you, but there is a service you can use for that, see http://stackoverflow.com/a/30582142/3385516 – mzulch Jan 13 '16 at 21:46
  • @mzulch I am using body-parser already. Still it makes the error. – Mani Jan 13 '16 at 22:04
  • @Loolooii As you see the res.body has a key value pair with the key being the entire form encoded data. – Mani Jan 13 '16 at 22:10
  • @mzulch Your second look is correct. If you can make that as an answer I can accept it. – Mani Jan 13 '16 at 22:15
  • Why don't you use application/json as Content-Type? – Loolooii Jan 14 '16 at 10:00

2 Answers2

2

Try sending data in encoded format with request headers as json.

var data = $.param({
            json: JSON.stringify({
                item_name : item.itemName
            })
        });
Abraham K
  • 624
  • 1
  • 8
  • 24
1

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);
});
Alexander Mikhalchenko
  • 4,525
  • 3
  • 32
  • 56
  • I am using body-parser module in the nodejs code already. But then my response contains res.body which has a key value pair with the key being the entire form encoded data. – Mani Jan 13 '16 at 22:11