错误还原:
bug-demo 点击 test2,请求参数丢失,# 后面的所有参数都没了
代码:
<body>
<a id="test1" href="javascript:void(0);">test1</a>
<br>
<a id="test2" href="javascript:void(0);">test2</a>
</body>
<script>
var test1 = document.querySelector("#test1")
test1.onclick = function (e) {
console.log('aaaa')
e.preventDefault()
// 正常的请求
location.href = "http://localhost:9090?abc=123"
}
var test2 = document.querySelector("#test2")
test2.onclick = function (e) {
console.log('bbb')
e.preventDefault()
// 错在这里,含有特殊字符 #
const testName = "你好测试#"
const params = {
name: testName,
pageIndex: 1,
pageSize: 10
}
const jstr = JSON.stringify(params)
// 报错的的请求
location.href = `http://localhost:9090?filter=${jstr}&token=123456`
}
</script>
修改后:
test2.onclick = function (e) {
console.log('bbb')
e.preventDefault()
// 错在这里,含有特殊字符 #
const testName = "你好测试#"
const params = {
name: encodeURIComponent(testName),
pageIndex: 1,
pageSize: 10
}
const jstr = JSON.stringify(params)
// 报错的的请求
location.href = `http://localhost:9090?filter=${jstr}&token=123456`
}
// 服务端,反序列化后,将 testName 还原
// ...
const {testName, ...otherParams } = JSON.parse(params)
const name = decodeURIComponent(testName)
// ...
原因:在第一个#后面出现的任何字符,都会被浏览器解读为位置标识符。这意味着,这些字符都不会被发送到服务器端
参考资料: