AJ Jones
AJ Jones

Reputation: 55

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

Upvotes: 0

Views: 812

Answers (3)

ridvanaltun
ridvanaltun

Reputation: 3020

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

Upvotes: 1

Rateb Habbab
Rateb Habbab

Reputation: 1789

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)

Upvotes: -1

Rani Sharim
Rani Sharim

Reputation: 620

# 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.

Upvotes: 1

Related Questions