Angular 7+ how to prevent query params special characters to be converted to hexcode?

Viewed 4161

Sample Endpoint:

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/

When I click on the endpoint above. My url gets converted to this...

https://localhost:4200/test/index.html?param1=username%2passw0rd&baseApi=https:%2F%2FsomeOtherService%2FAPIBase.jsp

as you can see inside the baseApi param the "/" was converted to "%2F" and the value "?INT/" was also removed.

How can I prevent the URL from converting the "/" and retain the "?INT/" value for the value inside the second parameter "baseApi".

Reference

2 Answers

You don't. It would break the internet if this was allowed.

More details:

  1. You can use URL decode on the backend API to convert the URL back to standard text.
  2. Never, ever pass passwords in the URL. It's literally one of the least secure things you can do.

on point 1: This is not always the case, many API frameworks automatically decode the query string.

If you need the full URL passed, ensure it's properly encoded:

console.log("https://localhost:4200/test/index.html?" + encodeURIComponent("param1=username%2passw0rd&baseApi=https://someOtherService/APIBase.jsp?INT/"));

https://localhost:4200/test/index.html?param1%3Dusername%252passw0rd%26baseApi%3Dhttps%3A%2F%2FsomeOtherService%2FAPIBase.jsp%3FINT%2F

You can't and shouldn't try to prevent special characters from being converted. The correct method is to deliberately encode them before sending the user off, but then decode them before reading the data. If you're using javascript, then you can do this via encodeURIComponent(string) and decodeURIComponent(string).

encodeURIComponent() will take any string, and convert it into a URL-friendly format.

decodeURIComponent() will take a converted string, and change it back into a regular format.

As to the reason why you shouldn't try to prevent them from being converted..... I'll quote Mozilla here:

For example, if a user writes "Jack & Jill", using encodeURIComponent the text will get encoded as "Jack %26 Jill". Without encoding, the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.

In other words, let's say you allowed symbols in your URL, and someone created a username called "Jack&baseApi=evilURL". Your URL would end up as

http://localhost:4200?username=Jack&baseApi=evilURL&baseApi=https://someOtherService

and I wouldn't want to be in your server's shoes, trying to guess whether the correct baseApi was "evilURL" or "someOtherService".

Related