11

When using Express' URL parameter functionality, it seems that parameters are automatically decoded. That is, percent-encoded entities are resolved to their normal form. %20 is replaced with a space.

However, a plus + is not replaced with a space. This is presumably because Express is using decodeURIComponent() internally, which also does not replace plus + with a space. Simple example code:

app.get('/:sourceFile', function (req, res, next) {
    console.log(req.params.sourceFile);
});

If you request /test%20test, then you get test test on the console. If you request /test+test, then you get test+test on the console.

Is there a way to change this mode of operation in Express 4? Is this a bug?

Brad
  • 159,648
  • 54
  • 349
  • 530
  • The decoding is currently (4.9.5) [defined in `router/layer.js`](https://github.com/strongloop/express/blob/4.9.5/lib/router/layer.js#L131-L151), using `decodeURIComponent()` as you suspected, and I don't see any options to modify that behavior (`decode_param` is defined and referenced only as a local within the module scope) without a PR. – Jonathan Lonowski Sep 30 '14 at 03:22
  • 1
    @JonathanLonowski Thanks for digging into that. I suppose I can create some middleware to replace `+` with `%20`, but it's a bit hacky. – Brad Sep 30 '14 at 03:23
  • Did you come up with a solution? – loveNoHate Feb 06 '15 at 08:03
  • Have you tried extending decodeURIComponent() and using it in your app. – mayankbatra Nov 04 '15 at 14:42
  • @liberalTGM I haven't, but I'd be reluctant to do so. I would have to override it globally, which could have an effect on other code outside my own. – Brad Nov 04 '15 at 18:59
  • You can extend it without changing the prototype. Instantiate a new instance wherever you need to use this function. – mayankbatra Nov 04 '15 at 19:59
  • @liberalTGM Its usage is built into Express. I'd have to modify Express, changing behavior for everything in my application relying on Express. – Brad Nov 04 '15 at 20:00

1 Answers1

4

You are trying to use + to represent a space in the "URI part" of your request. You can't do that. A plus sign is translated to a space only in query strings.

It is not a bug. In URI specs (page 12/13 https://www.rfc-editor.org/rfc/rfc3986), plus sign is a reserved character, not meant to be translated as a space.

Community
  • 1
  • 1
David Rissato Cruz
  • 3,347
  • 2
  • 17
  • 17