Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent url encoding in AngularJS route

Tags:

angularjs

Currently, when I pass my query string into the search() method of $location, my query string is uri encoded

Example

$location.path('/some_path').search({'ids[]': 1})

becomes

http://some_url/some_path?ids%5B%5D=1

I wonder if there's a way to get around this?

like image 391
trivektor Avatar asked Jan 31 '14 06:01

trivektor


People also ask

How to avoid encoding in URL Angular?

Angular2 by default uses encodeURIComponent() to encode queryParams in URL, you can avoid it by writing custom URL serializer and override default functionality.

What does encodeURIComponent do?

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Should I use encodeURI or encodeURIComponent?

encodeURIComponent should be used to encode a URI Component - a string that is supposed to be part of a URL. encodeURI should be used to encode a URI or an existing URL.

How to decode URL encoded string in Javascript?

Decoding in Javascript can be achieved using decodeURI function. It takes encodeURIComponent(url) string so it can decode these characters. 2. unescape() function: This function takes a string as a single parameter and uses it to decode that string encoded by the escape() function.


1 Answers

The problem is that .search() uses encodeUriQuery that internally uses encodeURIComponent and this function escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )

The current function inside Angular's source code:

/**
 * This method is intended for encoding *key* or *value* parts of query component. We need a custom
 * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
 * encoded per http://tools.ietf.org/html/rfc3986:
 *    query       = *( pchar / "/" / "?" )
 *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
 *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
 *    pct-encoded   = "%" HEXDIG HEXDIG
 *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
 *                     / "*" / "+" / "," / ";" / "="
 */
function encodeUriQuery(val, pctEncodeSpaces) {
  return encodeURIComponent(val).
             replace(/%40/gi, '@').
             replace(/%3A/gi, ':').
             replace(/%24/g, '$').
             replace(/%2C/gi, ',').
             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}

If that function had this additional replaces, then the brackets will keep unencoded:

replace(/%5B/gi, '[').
replace(/%5D/gi, ']').
like image 174
dimirc Avatar answered Nov 15 '22 06:11

dimirc