What is routing (hereinafter referred to as routing) in WEB development

In simple terms, routing is forwarded to the application program processed by the corresponding Controller according to the change of web page URL. Controller is commonly known as Controller, which is generally a function, so routing can also be regarded as the mapping between URL and function.

What is the semantic difference between “route” and “router”

A route to a user’s details page is a route to a user’s details page.

/user/:username= >getUserInfo(username){... }Copy the code

2. The router is a container that manages routes. To put it simply, route only maps urls to functions. When a URL is changed, the router searches for the corresponding function in the routing mapping table.

3. As for the relationship between the two, I think there is a good answer on Stack Overflow:

The router routes you to a route.

The difference between the server route and the front-end route

1. Server routing

When receiving an HTTP request from a client, the server finds the corresponding mapping function based on the REQUESTED URL, executes the function, and sends the return value of the function to the client. For the simplest static resource server, you can think of the mapping function of all urls as a file read operation. For dynamic resources, the mapping function may be a database read operation, some data processing, and so on.

For example, we use Express to define a server-side route

// Read file operations
app.get('/', (req, res) => {
  res.sendFile('index')})// Database read operation
app.get("/users", (req, res)=>{
  db.queryAllUsers()
    .then(data= > res.send(data))
})
Copy the code

Note that the Router not only determines whether the URL matches the route, but also whether the request is correct. For example, if we use the POST method to request the URL, the correct route will not be found.

2. Client routing

Client-side routing is often called front-end routing, also known as single-page application routing. The mapping function of client-side routing is usually to perform some DOM show and hide operations. In this way, different page components are displayed when accessing different paths.

From the perspective of users, the function of front-end routing is to realize the synchronization of URL and page state, that is, to display different contents and render different data under different URLS.

Therefore, as developers, we should develop routers that do:

  1. Change the URL without sending a request to the server;
  2. Detect URL changes and render corresponding states;
  3. Detects THE URL address and parses and matches the corresponding route.

Advantages and disadvantages of server routing and client routing

advantages disadvantages
Server routing 1. Good security;

2. Good SEO;
1. Poor coupling degree of code;

2. The server is under high pressure.

3. Each route switchover is accompanied by a request, resulting in poor user experience
Client routing 1. Good user experience;

2. Low coupling degree of code
1. SEO is poor;

2. The request is resend when the page is switched.

Five, front-end routing two implementation schemes

  1. Hash routing

    1.1. What is hash?

    A: Hash refers to the # and the part after # of the URL, for example, https://www.baidu.com#123, where #123 is a hash

    1.2. Why Hash Routing is Used?

    A: This is due to the nature of hash, which has the following features:

    • Hash is only a state of the client. When a request is sent to the server, the hash part will not be sent
    • Changes to the hash value add a history to the browser, so we can switch the hash value based on the browser’s back and forward buttons
    • We can usehashchangeEvent to listenhashThe change of the value

    1.3. How to Use Hash Routing?

    A: Hash routes can be used in two ways:

    • throughaTag and sethrefProperty so that when we click on the link, the URL changes and fireshashchangeEvent at this time if the page hasid 为 Hash valueClick the link to jump to the top of the corresponding element.
    <a href="#test" title=" test" >Copy the code
    • Another way is to usejavascriptDirectly on thelocation.hashThe assignment
    window.location.hash = "test"
    Copy the code

    1.4. Implementation of Hash routing

    Since the hash route is relatively simple to implement, I will simply publish the code:

    class HashRouter {
      constructor(list) {
        this.list = list
        this.init()
      }
    
      init() {
        this.routerHandler()
        window.addEventListener('hashchange', () = > {this.routerHandler()
        })
      }
    
      renderView(path) {
        const view =
          this.list.find(element= >element.path === path)? .component ||this.list.find(element= > element.path === The '*')? .componentdocument.querySelector('#app').innerHTML = view || '404'
      }
    
      routerHandler() {
        const path = this.getRouterPath()
        path === '/' && this.replace('/')
        this.renderView(path)
      }
    
      getRouterPath() {
        const hash = window.location.hash
        return hash ? hash.substring(1) : '/'
      }
    
      pushRoute(path) {
        window.location.hash = path
      }
    
      go(delta) {
        window.history.go(delta)
      }
    
      push() {
        window.history.go(1)
      }
    
      back() {
        window.history.back()
      }
    
      replace(path) {
        const currentUrl = window.location.href
        const replaceUrl = currentUrl.replace(/\/#(\/\S*)/, () = >` / #${path}`)
        window.location.replace(replaceUrl)
      }
    }
    Copy the code
    Hash routing complete test code
    // index.html
    
             
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Document</title>
      </head>
      <body>
        <button id="index">Home page</button>
        <button id="users">List of users</button>
        <button id="go">forward</button>
        <button id="back">back</button>
        <button id="replaceIndex">Replace with home page</button>
        <button id="replaceUsers">Replace it with the user page</button>
        <div id="app"></div>
        <script src="./index.js"></script>
      </body>
    </html>
    Copy the code
    // index.js
    class HashRouter {
      constructor(list) {
        this.list = list
        this.init()
      }
    
      init() {
        this.routerHandler()
        window.addEventListener('hashchange', () = > {this.routerHandler()
          console.log(window.history)
        })
      }
    
      renderView(path) {
        const view =
          this.list.find(element= >element.path === path)? .component ||this.list.find(element= > element.path === The '*')? .componentdocument.querySelector('#app').innerHTML = view || '404'
      }
    
      routerHandler() {
        const path = this.getRouterPath()
        path === '/' && this.replace('/')
        this.renderView(path)
      }
    
      getRouterPath() {
        const hash = window.location.hash
        return hash ? hash.substring(1) : '/'
      }
    
      pushRoute(path) {
        window.location.hash = path
      }
    
      go(delta) {
        window.history.go(delta)
      }
    
      push() {
        window.history.go(1)
      }
    
      back() {
        window.history.back()
      }
    
      replace(path) {
        const currentUrl = window.location.href
        const replaceUrl = currentUrl.replace(/\/#(\/\S*)/, () = >` / #${path}`)
    
        window.location.replace(replaceUrl)
      }
    }
    
    const routes = [
      { path: '/'.component: 'home' },
      { path: '/users'.component: 'User List'}]const router = new HashRouter(routes)
    
    document.querySelector('#go').onclick = (a)= > {
      router.push()
    }
    
    document.querySelector('#back').onclick = (a)= > {
      router.back()
    }
    
    document.querySelector('#index').onclick = (a)= > {
      router.pushRoute('/')}document.querySelector('#users').onclick = (a)= > {
      router.pushRoute('/users')}document.querySelector('#replaceIndex').onclick = (a)= > {
      router.replace('/')}document.querySelector('#replaceUsers').onclick = (a)= > {
      router.replace('/users')}Copy the code
  2. The history of routing

    2.1. What is a History route? The history route is implemented using the functionality provided by the window.history object in HTML5 to access the browser session history.

    2.2. Why use the history route?

    • The URL style is more beautiful
    • The history object providespushState å’Œ replaceStateThese two apis allow you to manipulate the browser’s history without refreshing
    • We can usepopstateEvent to listenurlBe careful, however, to usepushState å’Œ replaceStateThese two API route changes are not triggeredpopstateEvent that can be triggeredpopstateThe only eventgo,back,forwardThese three methods
    • Note that when using the history route, if the page is refreshed, the browser will send a request to the server. If the backend does not process the page, a 404 error will appear. Therefore, when using the history route, the backend needs to cooperate

    2.3. Implementation of history routing

    class HistoryRouter {
      constructor(list) {
        this.list = list
        this.init()
      }
    
      init() {
        this.routerHandler()
        window.addEventListener('popstate', () = > {this.routerHandler()
        })
      }
    
      renderView(path) {
        const view =
          this.list.find(element= >element.path === path)? .component ||this.list.find(element= > element.path === The '*')? .component// Mount the view to the page
        document.querySelector('#app').innerHTML = view || '404'
      }
    
      routerHandler() {
        const path = this.getRouterPath()
        this.renderView(path)
      }
    
      getRouterPath() {
        return window.location.pathname || '/'
      }
    
      pushRoute(path) {
        window.history.pushState(null.null, path)
        this.routerHandler()
      }
    
      go(delta) {
        window.history.go(delta)
      }
    
      push() {
        window.history.go(1)
      }
    
      back() {
        window.history.back()
      }
    
      replace(path) {
        window.history.replaceState(null.null, path)
        this.routerHandler()
      }
    }
    Copy the code
    Hash routing complete test code
    // index.html
    
             
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="Width = device - width, initial - scale = 1.0" />
        <title>Document</title>
      </head>
      <body>
        <button id="index">Home page</button>
        <button id="users">List of users</button>
        <button id="go">forward</button>
        <button id="back">back</button>
        <button id="replaceIndex">Replace with home page</button>
        <button id="replaceUsers">Replace it with the user page</button>
        <div id="app"></div>
        <script src="./index.js"></script>
      </body>
    </html>
    Copy the code
    // index.js
    class HistoryRouter {
      constructor(list) {
        this.list = list
        this.init()
      }
    
      init() {
        this.routerHandler()
        window.addEventListener('popstate', () = > {this.routerHandler()
        })
      }
    
      renderView(path) {
        const view =
          this.list.find(element= >element.path === path)? .component ||this.list.find(element= > element.path === The '*')? .component// Mount the view to the page
        document.querySelector('#app').innerHTML = view || '404'
      }
    
      routerHandler() {
        const path = this.getRouterPath()
        this.renderView(path)
      }
    
      getRouterPath() {
        return window.location.pathname || '/'
      }
    
      pushRoute(path) {
        window.history.pushState(null.null, path)
        this.routerHandler()
      }
    
      go(delta) {
        window.history.go(delta)
      }
    
      push() {
        window.history.go(1)
      }
    
      back() {
        window.history.back()
      }
    
      replace(path) {
        window.history.replaceState(null.null, path)
        this.routerHandler()
      }
    }
    
    const routes = [
      { path: '/'.component: 'home' },
      { path: '/users'.component: 'User List'}]const router = new HistoryRouter(routes)
    
    document.querySelector('#go').onclick = (a)= > {
      router.push()
    }
    
    document.querySelector('#back').onclick = (a)= > {
      router.back()
    }
    
    document.querySelector('#index').onclick = (a)= > {
      router.pushRoute('/')}document.querySelector('#users').onclick = (a)= > {
      router.pushRoute('/users')}document.querySelector('#replaceIndex').onclick = (a)= > {
      router.replace('/')}document.querySelector('#replaceUsers').onclick = (a)= > {
      router.replace('/users')}Copy the code

Five, the difference between the two schemes

Here digg friends @I am your superhero blog inside the table has been described in detail, we can learn from it to give you a reference:

Contrast point Hash routing The History of routing
Beautiful sex With the # character, ugly Concise and beautiful
compatibility >= Ie 8, other major browsers >= Ie 10, other major browsers
practical No changes to the server are required The server needs to coordinate the route Settings

Six, the last

Meng new blog, if there is any wrong, leave a message to discuss, thank you ~~

7. Refer to the article

  • Juejin. Cn/post / 684490…
  • My.oschina.net/u/4357035/b…