Home > Software engineering >  JavaScript fetch API call with string interpolation with string contains # always null
JavaScript fetch API call with string interpolation with string contains # always null

Time:10-16

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}`,

CodePudding user response:

# in a url is a special character which indicates a "fragment", which means a special part of the url which is an anchor in the page, of sorts. Thats why it breaks your code. ? And & are also special, and so are a few others.

You should url encode data that you pass in the url.

CodePudding user response:

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() like below:

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

Just encode the dynamic parts, encoding all URL at once not will work.

CodePudding user response:

Try use encodeURI() to the url string before fetching, like:

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

encodeURI(url)
  • Related