路由的history模式的研究

说起前端路由,下面这两种大家应该都比较熟悉了,

  • hash
  • history

hash

hash这块应该比较早的接触,当初我也是因为锚点才接触到的,也有比较多的问题

  1. hash部分后台无法从url 获取
  2. 对于锚点会出现冲突
  3. 服务器端无法准确跟踪前端路由信息

history

今天主要说下history, 上图

图上清晰的展示了地址栏里面的url 变化,最后我刷新页面之后404的问题。

window.addEventListener('popstate', function (event) {
             console.log('location: ' + document.location);
               console.log('popstate: ' + JSON.stringify(event.state) + ':' + history.length);
               if (!event.state) {
                   // let tm = Date.now();
                   // history.replaceState({tm: tm}, "title" + tm, '/' +tm);
               }
        })

window.addEventListener('click', function () {
    let tm = Date.now();
    history.pushState({tm: tm}, "title" + tm, '/' +tm);

    // history.pushState({tm: tm}, "title" + tm, '/history.html?a=' +tm)
})

原因是虽然这个时候把url改变了,由于是纯前端的业务,并没有对应后台的路由映射,刷新之后直接404了

vue-router的方案
https://router.vuejs.org/zh/guide/essentials/history-mode.html#%E5%90%8E%E7%AB%AF%E9%85%8D%E7%BD%AE%E4%BE%8B%E5%AD%90

nginx 配置方案

location / {
  try_files $uri $uri/ /index.html;
}


完美成功解决

文章来源: 路由的history模式的研究