DanHeidel
DanHeidel

Reputation: 671

What is the format of Express' req.params?

I've got a weird thing I'm running into with req.params while working with Express. It works fine for calling the subordinate properties - e.g.: res.json(req.params.paramName); gives me the desired paramName value. But when I tried to pass the entire res.params object to the client via res.json(req.params), I just get an empty array [] in the browser instead of the JSON object I was expecting. (res.send gives the same result.)

Looking a bit deeper, I dumped req.params to the console:

console.dir(req.params);

and got this:

[ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' ]

wut? Is that even syntactically possible in Javascript? If req.params is a simple object like the Express code and documentation indicate, I should be getting:

{ creator: '1', timeStart: '2', timeEnd: '3', dateDensity: '4' }

An array like what I'm getting above should even be possible, should it?

I did some sanity checks and passed a couple of test objects to the console as well:

console.dir([{foo:1}, {arr:2}, {gog:3}, {blah:4}]);
console.dir({foo:1, arr:2, gog:3, blah:4});

and the console dump gives me:

[ { foo: 1 }, { arr: 2 }, { gog: 3 }, { blah: 4 } ]
{ foo: 1, arr: 2, gog: 3, blah: 4 }

So console.dir is working OK.

Lastly, I hardcoded a:

res.json({foo:1, arr:2, gog:3, blah:4});

into my Express code and the browser dutifully gives me:

{
  "foo": 1,
  "arr": 2,
  "gog": 3,
  "blah": 4
}

Am I smoking crack here? What is going on with req.params?

Upvotes: 1

Views: 644

Answers (1)

Eric
Eric

Reputation: 97641

That's how v8 prints out arrays with string keys:

var myArr = [];
myArr.key = "oops";

Remember, [] instanceof Object is true.

req.params is an array, suggesting the possibility of positional params.

Upvotes: 2

Related Questions