2

I'm using Angular to POST to my API. As I'm dealing with CORS I have set the header as www-form-urlencoded to avoid the "pre-flight.

$http.post(url, {key1: value1, key2: value2},{"headers":{ "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }}).
  success(function(data, status, headers, config) {

  }).
  error(function(data, status, headers, config) {

  });

The problem now is that I can't seem to parse the object being POSTed even though I have this in my server.js which I thought would do the job:

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

I'm trying to access the POSTed values with req.body.key1 but I'm getting undefined

tommyd456
  • 10,443
  • 26
  • 89
  • 163
  • Do you have that line above where you define your `.post` route? – loganfsmyth Jan 04 '15 at 19:16
  • Sorry - what do you mean? – tommyd456 Jan 04 '15 at 19:18
  • In your route handler, add `console.dir({req:req,res:res})` to dump the contents of both the request and response to your console. Great way to debug/trace. – Rob Raisch Jan 04 '15 at 19:18
  • 1
    The console is showing that `req.body` is `{ '{"key1":"12345","key2":"abcde"}': '' }` – tommyd456 Jan 04 '15 at 19:22
  • 1
    I think @loganfsmyth means that the body parser module needs to be included in a certain position in your middleware "stack". Basically, before any routes is the most important, but I usually place it after most other middleware (except error handlers). – Jordan Kasper Jan 04 '15 at 19:22
  • body parser is before any routes - I've used `bodyParser.json()` happily which is on the line above. I think the POSTed data is malformed looking at my previous comment – tommyd456 Jan 04 '15 at 19:24

1 Answers1

3

You are not actually sending application/x-www-form-urlencoded data, so the middleware is getting confused. Setting the Content-Type header tells the server what kind of data you are sending, but you aren't actually changing the format of the data anywhere because nothing has told Angular that you want to send urlencoded data, so the server is still getting JSON.

This answer shows how to encode the data.

Community
  • 1
  • 1
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251