Express: Parsing for req.query changes + signs to spaces

Created on 19 Oct 2017  路  4Comments  路  Source: expressjs/express

You can observe this with a very simple app:
```var express = require('express');
var app = express();

app.get('/', function (req, res) {
console.log(req.originalUrl);
console.log(req.query);
res.send(req.query);
});

app.listen(7000);
`` If you go tohttp://localhost:7000/?thing=this+that, express receives the plus sign and still has it inoriginalUrl, butreq.querycontains{ thing: 'this that' }`.

This makes it so that if a float in the form of 1.7976931348623157e+308 is used in a query parameter, it cannot be parsed correctly in express.

question

Most helpful comment

Actually, scratch that, you can get the parse you desire with qs in our own parser function. The replacement is happening at

https://github.com/ljharb/qs/blob/037f3686e8f8eee456cf958c39ffd8a967d4ead5/lib/utils.js#L112

var express = require('express');
var qs = require('qs');

var app = express();

app.set('query parser', function (str) {
  return qs.parse(str, { decode: function (s) { return decodeURIComponent(s); } });
});

app.get('/', function (req, res) {
    console.log(req.originalUrl);
    console.log(req.query);
    res.send(req.query);
});

app.listen(7000);

I hope that helps!

All 4 comments

Looks like this is how our upstream dependency qs works:

$ node -pe 'require("qs").parse("thing=this+that")'
{ thing: 'this that' }

You can use the 'query parser' to set your own custom parser that behaves as you like, though. Not sure if there is something Express can do, at least as long as our dependency doesn't support that type of parse.

Actually, scratch that, you can get the parse you desire with qs in our own parser function. The replacement is happening at

https://github.com/ljharb/qs/blob/037f3686e8f8eee456cf958c39ffd8a967d4ead5/lib/utils.js#L112

var express = require('express');
var qs = require('qs');

var app = express();

app.set('query parser', function (str) {
  return qs.parse(str, { decode: function (s) { return decodeURIComponent(s); } });
});

app.get('/', function (req, res) {
    console.log(req.originalUrl);
    console.log(req.query);
    res.send(req.query);
});

app.listen(7000);

I hope that helps!

@jeversmann I think you should use '%2b', not '+'
I hope that helps!

I think decoder (not decode) option is appropriate in @dougwilson 's post.
I hope that helps!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Sunriselegacy picture Sunriselegacy  路  3Comments

ZeddYu picture ZeddYu  路  3Comments

cuni0716 picture cuni0716  路  3Comments

guyisra picture guyisra  路  3Comments

nove1398 picture nove1398  路  3Comments