JavaScript实现滚动更新URL分页号后刷新报Cannot GET错误如何解决
错误原因
你出现Cannot get testing.html/4错误的核心原因是:history.pushState仅在浏览器端修改地址栏显示,没有对应真实的服务器端静态资源或者路由规则。当你刷新页面时,服务器会尝试查找路径为testing.html/4的文件,这个文件不存在自然就返回404错误。
解决方案
方案1:改用哈希路由(无需修改服务器配置,最快实现)
把URL的分页号放到哈希(#)后面,比如改成testing.html#/4这种形式,哈希部分不会被发送到服务器,刷新时服务器还是会正常返回testing.html文件,你只需要在页面加载时读取哈希里的页码加载对应内容就行。
修改后的代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <style> .spinner { display: none; } </style> </head> <body style="font-size: 60px;"> <div class="news-content"></div> <div class="loading"> <p>Loading Please Wait</p> </div> <script> // 页面加载时读取哈希中的页码 function getInitCount() { const hash = window.location.hash.replace('#/', '') return hash ? parseInt(hash) : 0 } function loadData(count) { fetch('/index.json') .then(res => res.json()) .then(json => { if (count < json.length) { let text = document.createElement('p'); text.innerText = json[count].text; document.querySelector('.news-content').append(text); if (count > 0) { // 把页码放到哈希后 history.pushState(null, null, `#/${count}`) } } }); } let count = getInitCount() // 初始化加载到当前页码的所有内容 window.addEventListener('load', () => { for(let i=0; i<=count; i++) { loadData(i) } }); window.addEventListener('scroll', () => { if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) { count += 1; loadData(count) } }) </script> </body> </html>
方案2:配置服务器路由回退(保留原路径格式)
如果你就是要保持testing.html/4这种路径格式,需要在你的服务器上配置所有以testing.html/开头的请求都返回testing.html文件,前端再在页面加载时解析路径里的页码加载对应内容即可。
不同服务器配置参考:
- Nginx增加配置:
location ~ ^/testing.html/ { try_files /testing.html =404; }
- Apache可以在.htaccess里增加重写规则
- Node.js服务可以增加对应路由规则,所有匹配
/testing.html/*的请求都返回testing.html文件
前端只需要新增读取路径页码的逻辑即可:
function getInitCount() { const pathArr = window.location.pathname.split('/') const lastPart = pathArr[pathArr.length - 1] return /^\d+$/.test(lastPart) ? parseInt(lastPart) : 0 }
初始化加载逻辑和方案1一致,循环加载到当前页码的所有内容即可。
内容的提问来源于stack exchange,提问作者kentury
相关产品推荐
相关产品推荐

