0

Im trying to query a record from database using this criteria: VITAMINS + ZINC 100MG/10MG PER 5ML SYRUP

This is what my request url looks like:

http://localhost:4200/api/search?key=VITAMINS%20+%20ZINC%20100MG/10MG%20PER%205ML%20SYRUP

Here is my express router looks like:

router.get('/search', (req, res, next) => {
  const query = req.query;
  console.log(query.key);

  .... omitted

});

The problem here is i can't retain the + special character and thus end up getting this log printed which is not the original criteria inside the router.

VITAMINS   ZINC 100MG/10MG PER 5ML SYRUP
Shift 'n Tab
  • 8,808
  • 12
  • 73
  • 117
  • Did you tried encoding the query string ? https://stackoverflow.com/questions/16622504/escaping-ampersand-in-url – Ankit May 22 '18 at 07:29
  • i tried decodeURIComponent but still the same as the logged output – Shift 'n Tab May 22 '18 at 07:30
  • 1
    I meant, if you have control of code generating the URL, you can use `encodeURIComponent()` at client side combined with decoding at server side. – Ankit May 22 '18 at 07:34
  • @Ankit hey i was able to solve my problem and thanks to your idea. first i did a `encodeURIComponent` in the client then does a `decodeURIComponent` in the server to render the same criteria – Shift 'n Tab May 22 '18 at 07:35
  • lot of thanks... mind to make that an answer? will gladly accept. – Shift 'n Tab May 22 '18 at 07:35

1 Answers1

2

In terms of URI, + character is one of the reserved characters.

When a character from the reserved set (a "reserved character") has special meaning (a "reserved purpose") in a certain context, and a URI scheme says that it is necessary to use that character for some other purpose, then the character must be percent-encoded.

In your case, query string needs to be percent-encoded before hitting the URL at client side :

encodeURIComponent("VITAMIN + ZINC")

And then at server side (i.e. express) decode the query using decodeURIComponent().

Ankit
  • 1,471
  • 17
  • 29