Shai Mishali
Shai Mishali

Reputation: 9382

Express.JS url parameters aren't parsed

I have the following route configured

app.put('/v1/users/:uid', function(req, res){
            res.send(req.route);
        });

When sending a PUT request to http://localhost:3000/v1/users/blablabla

I get the following output back

{
   "path": "/v1/users/:uid",
   "method": "put",
   "callbacks": [
       null
   ],
   "keys": [
       {
           "name": "uid",
           "optional": false
       }
   ],
   "regexp": {},
   "params": []
}

As you see the params array seems to be empty instead of having the value "blablabla". But the "uid" key appears in keys, which I don't really know what to make of.

Would appreciate any suggestions.

Upvotes: 0

Views: 525

Answers (2)

Laurent Perrin
Laurent Perrin

Reputation: 14881

OK, the trick is that Express uses a sparse array to parse the params.

When you pass it to req.send, the array is converted with JSON.stringify. Here's what happens in a JS shell:

> var params = [];
> params['uid'] = 1;
> params;
[ uid: 1 ]
> JSON.stringify(params);
'[]'

What's happening is that adding a non-numeric to an array does not change its length:

> params.length
0

So the new value is ignored by JSON.stringify.

Upvotes: 1

Shai Mishali
Shai Mishali

Reputation: 9382

Well this is the weirdest thing I've seen.

When doing a console.log(req.params) or console.log(req.route.params) I get an empty array response ([]).

But when doing a console.log(req.params.uid) I get the value! Thats extremely weird but hey, it works :)

Cheers.

Upvotes: 0

Related Questions