JavaScript fetch API 使用字符串插值调用,字符串包含 # 始终为 null
JavaScript fetch API call with string interpolation with string contains # always null
如果我将字符串作为“testabc#”传递,它会在通往控制器的路径上的某处中断。我不确定为什么 # 会导致我出现问题。这是导致问题的 JavaScript 中的关键工作吗?我已经尝试了所有其他不同的特殊字符,它们工作得很好。有没有其他人遇到过这个问题。
`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`,
url 中的 # 是一个特殊字符,表示“片段”,这意味着 url 的特殊部分,它是页面中的锚点。这就是为什么它会破坏您的代码。 ?还有&也很特别,还有几个也很特别
您应该 url 对您在 url 中传递的数据进行编码。
在获取之前尝试对 url 字符串使用 encodeURI()
,例如:
var url = `/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`
encodeURI(url)
锚点 (#) 是 URL 的一项功能,称为片段,用于内部页面引用。使用问号 (?) 和符号 (&) 可以像锚点一样破坏您的 HTTP 请求,因为所有这些都是 URL 功能并且它会改变 URL 行为。
要避免此类错误,您必须使用 encodeURI()
或 encodeURIComponent()
,如下所示:
与 encodeURIComponent()
:
var url = `/api/Controller/UpdatePassword?currentPassword=${encodeURIComponent(currentPassword.value)}&newPassword=${encodeURIComponent(newPassword.value)}&confirmPassword=${encodeURIComponent(confirmPassword.value)}`
与 encodeURI()
:
var url = encodeURI(`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`)
如果我将字符串作为“testabc#”传递,它会在通往控制器的路径上的某处中断。我不确定为什么 # 会导致我出现问题。这是导致问题的 JavaScript 中的关键工作吗?我已经尝试了所有其他不同的特殊字符,它们工作得很好。有没有其他人遇到过这个问题。
`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`,
# 是一个特殊字符,表示“片段”,这意味着 url 的特殊部分,它是页面中的锚点。这就是为什么它会破坏您的代码。 ?还有&也很特别,还有几个也很特别
您应该 url 对您在 url 中传递的数据进行编码。
在获取之前尝试对 url 字符串使用 encodeURI()
,例如:
var url = `/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`
encodeURI(url)
锚点 (#) 是 URL 的一项功能,称为片段,用于内部页面引用。使用问号 (?) 和符号 (&) 可以像锚点一样破坏您的 HTTP 请求,因为所有这些都是 URL 功能并且它会改变 URL 行为。
要避免此类错误,您必须使用 encodeURI()
或 encodeURIComponent()
,如下所示:
与 encodeURIComponent()
:
var url = `/api/Controller/UpdatePassword?currentPassword=${encodeURIComponent(currentPassword.value)}&newPassword=${encodeURIComponent(newPassword.value)}&confirmPassword=${encodeURIComponent(confirmPassword.value)}`
与 encodeURI()
:
var url = encodeURI(`/api/Controller/UpdatePassword?currentPassword=${currentPassword.value}&newPassword=${newPassword.value}&confirmPassword=${confirmPassword.value}`)