Express URL parameter feature doesn't decode plus (+) as space
Asked Answered
B

1

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?

Bravar answered 30/9, 2014 at 1:15 Comment(7)
The decoding is currently (4.9.5) defined in router/layer.js, 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.Zephan
@JonathanLonowski Thanks for digging into that. I suppose I can create some middleware to replace + with %20, but it's a bit hacky.Bravar
Did you come up with a solution?Aeschylus
Have you tried extending decodeURIComponent() and using it in your app.Dependency
@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.Bravar
You can extend it without changing the prototype. Instantiate a new instance wherever you need to use this function.Dependency
@liberalTGM Its usage is built into Express. I'd have to modify Express, changing behavior for everything in my application relying on Express.Bravar
S
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.

Sherburne answered 11/11, 2015 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.