1

I'm using the express.bodyParser middleware and I'm trying to convert req.body object into a POST encoded string. Is there a way of doing this?

Example:

Name: Jonathan Doe
Age: 23
Formula: a + b == 13%!

Becomes:

Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
Trevor
  • 1,333
  • 6
  • 18
  • 32

2 Answers2

2

Node has a module for this.

var qs = require('querystring');
...
console.log(qs.stringify(req.body));

But connect/express store the raw body in req.rawBody anyway.

chjj
  • 14,322
  • 3
  • 32
  • 24
0

I think this should be fairly simple - you should be able to do it the same way you would do in a browser. This function converts all string/number members of an object/array to a string that can be used as a POST body:

var objectToPostBody = function (object) {
  var i, out;
  if (!object) {
    return false;
  }
  out = [];
  for (i in object) {
    if (typeof object[i] === 'string' || typeof object[i] === 'number') {
      out[out.length] = encodeURIComponent(i) + '=' + encodeURIComponent(object[i]);
    }
  }
  return out.join('&');
};

If you want to handle sub-arrays/sub-objects the function would get more complicated, but for what you describe above I think that should do the trick.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174