Why whenever I run encodeURIComponent('my_url')
, I get a weird looking URL like https://r[...]
... Why is that and how do I solve it?
Btw, I'm using Windows.
function createSharedAccessToken(uri, saName, saKey) {
uri = // '...'
saName = // '...'
saKey = // '...'
if (!uri || !saName || !saKey) {
throw "Missing required parameter";
}
var encoded = encodeURIComponent(uri);
var now = new Date();
var week = 60 * 60 * 24 * 7;
var ttl = Math.round(now.getTime() / 1000) week;
var signature = encoded '\n' ttl;
var signatureUTF8 = utf8.encode(signature);
var hash = crypto.createHmac('sha256', saKey).update(signatureUTF8).digest('base64');
return 'SharedAccessSignature sr=' encoded '&sig='
encodeURIComponent(hash) '&se=' ttl '&skn=' saName;
}
CodePudding user response:
The type of 'wierd looking url' you shared is eactly what encodeURIComponent is designed to return.
all character except
A-Z a-z 0-9 - _ . ! ~ * ' ( )
get replaced by escape sequences.
For example, any spaces
become
and /
becomes /
.
A typical URL, processed by encodeURIComponent, might look like this:
https://stackoverflow.com
When you are ready to display the original string, you simply use decodeURIComponent to reverse the process:
decodeYRIComponent('https://stackoverflow.com');
// becomes: https://stackoverflow.com
CodePudding user response:
It is well explained here, why we need to encode the URL
if a user writes Jack & Jill, the text may get encoded as Jack & Jill. Without encodeURIComponent() the ampersand could be interpreted on the server as the start of a new field and jeopardize the integrity of the data.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent
If we need it in human readable form, we always have https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI