Server summary & single page development concepts

Server language

What is the server language? It is a language that runs on a server and can be used to read and write databases and write service logic.

I don’t want to make it too complicated, because it boils down to doing these two things.

As for the choice of server-side language, it is based on the combination of business and their own capabilities. For example, as a front-end developer, I prefer Node as the server development language because JS can write the backend.

For the record, Node is not a language per se, but a development environment, based on Google’s V8 engine, that allows JavaScript to run on a server. Give JavaScript more capabilities than browser scripting, such as IO operations.

Ii. Database

The function of a database is to store data persistently.

This project choose MySQL as the database, because it as the established database, online solution is more, if the problems encountered in the development process, can easily find themselves on the search engine problem solution, for the novice, fluency is the key project, after completing a set of project development, Of course, you can try to choose other databases that are more interesting, but I won’t expand the description here.

This tutorial uses the egg-mysql plug-in for database operations. Sequelize is officially recommended for more complex projects. The idea is to get you started quickly and not to introduce too many complex concepts. If you need to deal with more complex projects later in your learning process, you can use Sequelize.

Iii. Project analysis

The whole project is based on the egg.js as the superstructure, through some predefined development forms provided by egg.js, the development of the following ten interfaces is easily completed:

The project is small, but it covers a few key points:

  • Multi-user authentication
  • A set of add, delete, change and check
  • Secondary processing of table data (chart)
  • Making list pages
  • File data upload

To describe it as “a sparrow is small but has all five organs”, hahaha.

If you want to expand some new functions on this basis, such as circle of friends, notes, blog, etc., can be based on the project for secondary development, because the multi-user authentication shelf has been built, the follow-up is to add tables, and some business logic processing.

Of course, if you want to do something more complicated, like a mall. The content involved may be more, just on the backstage editing of the commodity module, the front display, involves SKU, shopping cart, inventory processing, multi-picture uploading, detailed editing, type screening and so on. This is a test of knowledge and problem solving ability.

Four. Front-end framework single page concept

The server side of the content is basically over, from here, into the front part of the actual combat. React is used as the front-end framework in the front part of this project, so first understand what single page is, how it realizes the switch between page components, and the principle of routing.

  • Traditional pages DOM straight out
  • Single page principle
  • Front-end routing implementation

1. The single page

Since the advent of the big three framework era, the traditional multi-page development has gradually faded out of people’s attention. In order to better understand the present, it is necessary to know its past.

2. Traditional pages

There is no problem with the name, all the entire project is DOM straight out of the page, it is called “traditional page” (SSR belongs to the first screen straight out, HERE I do not think it is the category of traditional page). So what is DOM straight out? To put it simply, the browser initiates a request after entering the url, and the returned HTML page is the final rendering effect, that is, DOM straight out. And every time you click to jump to the page, the HTML resource will be requested again. Hearing is but believing, seeing is believing. Using this address as an example, verify the following statement.

www.cnblogs.com/han-1034683…

If you look at it, you can see what the picture is about. Yes, the blog garden is a traditional page built into the website, each load page, will return HTML resources and CSS inside the static resources, combined into a new page. When opened, it looks like the following:

What images or text can be seen on a web page, you can find the corresponding HTML structure in the above image, which is also a traditional page, namely DOM straight out.

3. The single page

Times are progressing, technology is developing, facing the increasing demand for web pages, web pages began to modular, componentized road. The resulting code is difficult to maintain, uncontrollable, difficult to iteration and other phenomena. This situation has led to the emergence of many excellent modern front-end frameworks, notably React, Vue, Angular and other well-known single-page application frameworks. One thing these frameworks have in common is “rendering pages through JS”. For example, using these single-page frameworks, the HTML page basically has a SINGLE DOM entry, which looks something like this:

All page components are mounted under the

node by running the app.js script at the bottom of the image above. Mount this step with an extremely simple JS:

<body>
<div id="root"></div>
<script>
  const root = document.getElementById('root') // Get the root node
  const divNode = document.createElement('div') // Create a div node
  divNode.innerText = 'Hello,World! ' // Insert content
  root.appendChild(divNode) // Insert the root node
</script>
</body>
Copy the code

All nodes are created using the createElement method and eventually inserted into the root node as appendChild.

So the question is, what if there are a dozen pages that need to do this?

At this time “front-end routing” arises at the historic moment, its emergence is to solve the single page site multiple page components switch. Switch the browser address path to match the corresponding page component. To understand the process, take a look at an ugly picture:

The “front-end route” matches the corresponding page component based on the pathname change in the browser address bar. It is then plugged into the root node by creating a DOM node

. This has the effect of no refresh page switching, which is why modern frameworks like React, Vue, and Angular have their own “life cycle” when creating page components.

4. Implementation principle of routing

Vue-router and React-Router are two popular frameworks for front-end routing, but their logic is still the same.

By analyzing the realization principle of “hash mode” and “history mode”, we have a deeper understanding of the principle of front-end routing.

Hash pattern

The browser provides the native listener event hashchange, which can listen for the following changes:

  • Click on theaTAB to change the browser address.
  • The browser’s forward and backward behavior.
  • throughwindow.locationMethod to change the browser address.

Next, take advantage of these features to implement a simple hash route: run online

<! DOCTYPEhtml>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Hash pattern</title>
</head>
<body>
<div>
  <ul>
    <li><a href="#/page1">page1</a></li>
    <li><a href="#/page2">page2</a></li>
  </ul>
  <! Where to render the corresponding component -->
  <div id="route-view"></div>
</div>
<script type="text/javascript">
  // The hashchange listener event is not executed the first time it is loaded, but once by default
  // DOMContentLoaded is triggered when the browser DOM has finished loading
  window.addEventListener('DOMContentLoaded', Load)
  window.addEventListener('hashchange', HashChange)
  // Display the node of the page component
  var routeView = null
  function Load() {
  routeView = document.getElementById('route-view')
  HashChange()
}
  function HashChange() {
  // Each time the hashchange event is triggered, the hash value of the current browser address is obtained via location.hash
  // Display different contents according to different paths
  switch(location.hash) {
  case '#/page1':
  routeView.innerHTML = 'page1'
  return
  case '#/page2':
  routeView.innerHTML = 'page2'
  return
  default:
  routeView.innerHTML = 'page1'
  return}}</script>
</body>
</html>
Copy the code

Of course, this is a very simple implementation, a real hash pattern, but also to take into account a lot of complex situations, you are interested to see the source code.

History Mode

History mode is a bit more troublesome than hash mode because history mode relies on the native event popState. Here’s what MDN explains:

Fact: pushState and replaceState are new HTML5 apis that are powerful enough to change the browser address without refreshing the page. This is an important way to change the address bar without refreshing the page.

Click events that include a tags are also not listened for by PopState. You need to figure out a way around this to implement the History pattern.

PushState pushState pushState pushState pushState pushState pushState pushState pushState pushState pushState pushState pushState pushState Then manually execute the popState event callback function to match the appropriate route. The logic may be a little tricky, but here’s the code: online address

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>The History mode</title>
</head>
<body>
<div>
    <ul>
        <li><a href="/page1">page1</a></li>
        <li><a href="/page2">page2</a></li>
    </ul>
    <div id="route-view"></div>
</div>
<script type="text/javascript">
    window.addEventListener('DOMContentLoaded', Load)
    window.addEventListener('popstate', PopChange)
    var routeView = null
    function Load() {
        routeView = document.getElementById('route-view')
        // The popState callback is executed once by default, matching the page component once
        PopChange()
        // Get all the a tag nodes with href attributes
        var aList = document.querySelectorAll('a[href]')
        // Iterate through the a tag node array to block the default event and add the click event callback function
        aList.forEach(aNode= > aNode.addEventListener('click'.function(e) {
            e.preventDefault() // Block the default event for the A tag
            var href = aNode.getAttribute('href')
            // Manually modify the browser address bar
            history.pushState(null.' ', href)
            // Manually modify the address bar with history.pushState,
            // PopState does not listen for changes in the address bar, so you need to manually execute the PopChange callback function
            PopChange()
        }))
    }
    function PopChange() {
        console.log('location', location)
        switch(location.pathname) {
            case '/page1':
                routeView.innerHTML = 'page1'
                return
            case '/page2':
                routeView.innerHTML = 'page2'
                return
            default:
                routeView.innerHTML = 'page1'
                return}}</script>
</body>
</html>
Copy the code

Note that you can’t open a static file directly in the browser, you need to use the Web service to launch the port to browse the url. The default protocol turned on is file, which is not listened on by PopState.

In live.

The above content, basically on the front-end single page implementation principle has a rough prototype, more in-depth study or need to analyze the source code of the framework.