路由的原理

一,路由原理

1.定义:端到端的传输路径

2.路由的结构

《路由的原理》

  • protocal:协议头
  • hostname:域名
  • port:端口
  • pathname:路径名
  • search:查询参数
  • hash:哈希,定位锚点,不会传输给服务器

3.查询路由信息:window.location

4.路由前端路由和后端路由两种

  • 后端路由:资源路径,其返回结果可能是图片、json、html等

《路由的原理》

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

《路由的原理》

5.前端路由的特性

  • 改变url 不向服务器发送请求。

注:这里的改变指的是js 动态改变,而不是对页面的刷新。

  • 前端能够监听url 变化。
  • 前端能够解析url 信息,并执行相应操作。

6.前端路由的实现方式有两种:hash,history

二, hash 实现前端路由

1.api

  • window.location.assign:改变浏览器地址,生成一条新的历史记录
  • window.location.replace:改变浏览器地址,不会生成新的历史记录
  • window.location.onhashchange:改变路由hash 值的监听方法

2.运作流程

《路由的原理》

3.特点:

  • 占用锚点功能
  • 兼容性好

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.运作流程

《路由的原理》

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中,作为后端项目的一部分,此后端项目中,还会有其它的项目。

《路由的原理》

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…

    原文作者:buglas
    原文地址: https://segmentfault.com/a/1190000020240728
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞