路由的原理

一,路由原理

1.定義:端到端的傳輸路徑html

2.路由的結構前端

clipboard.png

  • protocal:協議頭
  • hostname:域名
  • port:端口
  • pathname:路徑名
  • search:查詢參數
  • hash:哈希,定位錨點,不會傳輸給服務器

3.查詢路由信息:window.locationjson

4.路由前端路由和後端路由兩種後端

  • 後端路由:資源路徑,其返回結果多是圖片、json、html等

clipboard.png

  • 前端路由:前端自身解析路由信息

clipboard.png

5.前端路由的特性api

  • 改變url 不向服務器發送請求。

注:這裏的改變指的是js 動態改變,而不是對頁面的刷新。瀏覽器

  • 前端可以監聽url 變化。
  • 前端可以解析url 信息,並執行相應操做。

6.前端路由的實現方式有兩種:hash,history服務器

二, hash 實現前端路由

1.apiapp

  • window.location.assign:改變瀏覽器地址,生成一條新的歷史記錄
  • window.location.replace:改變瀏覽器地址,不會生成新的歷史記錄
  • window.location.onhashchange:改變路由hash 值的監聽方法

2.運做流程koa

clipboard.png

3.特色:async

  • 佔用錨點功能
  • 兼容性好

4.示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>hash</title>
    <style>
        #space{height: 1500px;background-color: #f7ead9}
    </style>
</head>
<button id="btn1">assign hash</button>
<button id="btn2">replace hash</button>
<a href="#hash">a 標籤經過href追蹤id爲hash的DOM 節點</a>
<div id="space"></div>
<h3 id="hash">hash 連接的目標</h3>
<body>
    <script>
        window.addEventListener('hashchange',function(event){
            console.log(event);
        })
        document.getElementById('btn1').onclick=function(){
            window.location.assign('#/hash');
        }
        let n=0;
        document.getElementById('btn2').onclick=function(){
            window.location.replace('#/hash'+n++);
        }
    </script>
</body>
</html>

三, history 實現前端路由

1.api

  • window.history.pushstate:改變瀏覽器地址,生成一條新的歷史記錄
  • window.history.replacestate:改變瀏覽器地址,並覆蓋當前歷史記錄
  • window.history.onpopstate:瀏覽器後退或前進時觸發

2.特色

  • 兼容到ie10
  • 路由與後端無異,能夠直接改變路徑名稱,而不是隻能改變hash 值
  • 須要後端支持,由於路由在刷新頁面的時候仍是會向服務器發起請求,若服務器沒有相應路徑,就會報404 錯誤

3.運做流程

clipboard.png

4.示例

<button id="btn1">assign hash</button>
<button id="btn2">replace hash</button>
<body>
    <script>
        window.addEventListener('popstate',function(event){
            console.log(event);
        })
        document.getElementById('btn1').onclick=function(){
            window.history.pushState(null,null,'/p1');
        }
        let n=0;
        document.getElementById('btn2').onclick=function(){
            window.history.replaceState(null,null,'/r'+n++);
        }
    </script>
</body>

四, 後端支持支持history

1.以koa 爲例。

routeTest 文件夾是帶有history 路由功能的項目文件,置入一個後端項目koa-test中,做爲後端項目的一部分,此後端項目中,還會有其它的項目。

clipboard.png

2.在app.js 軸配置後端路由

router.get('/routeTest',routeTest);
router.get('/routeSecond',routeTest);
async function routeTest(ctx) {
    await ctx.render('routeTest/index');
}
  • 在前端向服務端發起' http://127.0.0.1:300/routeTest'和' http://127.0.0.1:300/routeSecond' 請求的時候,都會打開routeTest 項目下的index.html文件。這樣在刷新頁面的時候,就不會報404 的錯誤了。
  • 完整app.js 代碼
const Koa=require('Koa');
const KoaRouter=require('koa-router');
const path=require('path');
const render=require('koa-ejs');
const app=new Koa();
const router=new KoaRouter();

render(app,{
    root:path.join(__dirname,'views'),
    layout:'layout',
    viewExt:'html',
    cache:false,
    debug:false
})
router.get('/',index);
router.get('/routeTest',routeTest);
router.get('/routeSecond',routeTest);
async function index(ctx) {
    await ctx.render('index', {
        msg: 'Free is my love....',
    });
}
async function routeTest(ctx) {
    await ctx.render('routeTest/index');
}
app.use(router.routes()).use(router.allowedMethods());
app.listen(300,()=>{
    console.log('server start...');
})

參考連接: https://ke.qq.com/course/3600...

相關文章
相關標籤/搜索