Search code examples
javascriptfetch

JavaScript fetch API call with string interpolation with string contains # always null


If I pass a string as "testabc#" it breaks somewhere on the way route to the controller. I'm not sure why the # is causing me the issue. Is this a key work in JavaScript causing the issue? I have tried all other different specials characters and they work just fine. Has anyone else come across this issue.

`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`,

Solution

  • Anchor (#) is a feature of URL called fragment and it is used for internal page references. Using a question mark (?) and ampersand (&) can break your HTTP request like an anchor does because all of these things are URL features and it changes URL behavior.

    To avoid this kind of error you must use encodeURI() or encodeURIComponent() like below:

    with encodeURIComponent():

    var url = `/api/Controller/UpdatePassword?currentPassword=${encodeURIComponent(currentPassword.value)}&newPassword=${encodeURIComponent(newPassword.value)}&confirmPassword=${encodeURIComponent(confirmPassword.value)}`
    

    with encodeURI():

    var url = encodeURI(`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`)