2

I have below running in nodejs 16.18.x

app.get('/CheckPlan', (req, res) => {
 res.setHeader('Content-Type', 'application/json');  
var dataToSend;
console.log("1111", req.query.token);
}

calling this from postman http://localhost:3000/CheckPlan?key=C3363&token=abc+TI4

the problem is the + in token is missing. what i see is only 'abc T14'

anyone has any idea ?

not sure why the + is missing from the passed argument

Lin Du
  • 88,126
  • 95
  • 281
  • 483
beisaikong
  • 21
  • 1
  • Does this answer your question? [How to encode the plus (+) symbol in a URL](https://stackoverflow.com/questions/5450190/how-to-encode-the-plus-symbol-in-a-url) – AngYC Apr 25 '23 at 08:24

1 Answers1

0

From the req.query doc, we know Express framework uses the qs package as its default query parser.

A very popular query string parser is the qs module, and this is used by default.

The default value of query parser application setting is "extended", see #app.settings.table, it will use the qs module as its query parser.

Let's take a look the source code, express compile the query parse at this line 4.18.2/lib/utils.js#L200

The parseExtendedQueryString implementation:

function parseExtendedQueryString(str) {
  return qs.parse(str, {
    allowPrototypes: true
  });
}

As you can see, it uses the qs module to parse the query string.

Let's go back to your question, ?key=C3363&token=abc+TI4 query string is invalid in the first place because the + sign is special in a query string.

+ sign has a semantic meaning in the query string. It is used to represent a space.

For more information, see this question Plus sign in query string

So, if you want to keep the + sign as a part in the parsed value, you need to encode the query string using encodeURIComponent like this before sending the HTTP request:

const obj = qs.parse(`key=C3363&token=${encodeURIComponent('abc+TI4')}`)
console.log(obj); // {key: "C3363", token: "abc+TI4"}
Lin Du
  • 88,126
  • 95
  • 281
  • 483