前端路由和服务端路由

2022-10-16 计算机网络 大约 1 分钟

# 服务端路由

实现一个路由根据浏览器输入不同的 url返回不同的页面

const app = require('express')();
const fs = require('fs');
const path = require('path');
// pages 文件夹下有 list、detal、spa 3个html页面
const pageDir = path.resolve(__dirname, "pages");
const htmls = fs.readdirSync(pageDir);

function displayHtmlFile(name) {
  return (req, res) => {
    const filePath = path.resolve(pageDir, name + ".html");
    res.sendFile(filePath);
  }
}

htmls.forEach(file => {
  const [name, ext] = file.split('.');
  app.get('/' + name, displayHtmlFile(name));
});

app.listen(3000);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 前端路由(SPA)

前端改变 url 地址不请求服务端由客户端处理并渲染页面。

// 服务端代码
const app = require('express')()
const path = require('path')
const { reset } = require('nodemon')

const htmlFile = path.resolve(__dirname, "pages/spa.html")
// /proucts /product/123 -> 
app.get(/\/product(s|\/\d+)/, (req, res) => {
  res.sendFile(htmlFile)
})

app.listen(3000)
1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <style>
      a {
        color :skyblue;
        cursor: pointer;
      }
    </style>
  </head>
<body>
<h2>单页面应用示例</h2>
<div id='content'></div>
<ul>
  <li><a onclick='route("/products")'>列表</a></li>
  <li><a onclick='route("/product/123")'>详情</a></li>
</ul>
<script>

function pageList(){
  const html = `
  <ul>
    <li>Apple</li>
    <li>TicTok</li>
    <li>Alibaba</li>
  </ul>
  `
  document.getElementById('content').innerHTML = html
} 

function pageDetail(){
  document.getElementById('content').innerHTML = "DETAIL" 
}

function route(path) {
  history.pushState(null, null, path)
  matchRoute(pages,window.location.href)
}

const pages = [
  {
    match : /\/products/,
    route: pageList
  },
  {
    match : /\/product\/\d+/,
    route : pageDetail
  }
]

function matchRoute(pages, href) {
  const page = pages.find(page =>page.match.test(href))
  page.route()
}

// 点击浏览器前进后退按钮时触发
window.onpopstate= function(){
  matchRoute(pages, window.location.href)
}

matchRoute(pages, window.location.href)
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64

此案例代码模拟单页 spa 应用。

上次编辑于: 2023年7月4日 09:36