Server-side rendering basics

Preface

The essence of rendering is the parsing and replacement of strings. For developers, the client requests back-end interface data, and then binds the data to the page through template binding syntax, and finally presents it to the user. This process can be regarded as Rendering, this article does not focus on how to render, but where to render.


1. Traditional server-side rendering page

In ASP, PHP, JSP, and later in the era of relatively advanced server-side frameworks with some template engines, web page rendering is done on the server side, that is, the required data is combined with page template rendering on the server side. It is HTML, and then the complete page is returned to the client. The client is only responsible for page rendering. This mode is only suitable for web pages that are not complex. The workflow is as follows:
Insert picture description hereFor those of us who are proficient in using modern front-end technologies such as vue, react, and angular In other words, this method is unfamiliar. Use a node to simulate it.
Ready to work:

  1. Create a new project
  2. Use yarn init to initialize the project
  3. Install express, art-template
  4. Create a new data.json file as the data source
  5. Create a new index.html file as a page template
  6. Create a new server.js file to build the server

Under the content of the server.js file:

const express = require("express"); //快速创建web服务
const fs = require("fs"); //读取文件
const artTemplate = require("art-template"); //服务端渲染引擎
const app = express();

app.get("/", (req, res) => {
    
    
    const tempStr = fs.readFileSync("./index.html", "utf-8"); //获取页面模板
    const data = JSON.parse(fs.readFileSync("./data.json", "utf-8")); //获取数据
    const html = artTemplate.render(tempStr, data); //将页面模板和数据渲染成html
    res.send(html); //把渲染结果发送到客户端
});

app.listen(8080);

Contents of index.html file:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>传统服务端渲染</title>
    </head>
    <body>
        <h1>{
    
    {
    
     title1 }}</h1>
        <ul> 
            {
    
    {
    
     each list }}
            <li>{
    
    {
    
     $value.id }}.{
    
    {
    
     $value.title }}: {
    
    {
    
     $value.content }}</li> 
            {
    
    {
    
     /each }}
        </ul>
    </body>
</html>

The contents of the data.json file:

{
    
    
    "title1": "Prerequisites",
    "list": [
        {
    
    
            "id": 1,
            "title": "node",
            "content": "the latest LTS version installed"
        },
        {
    
    
            "id": 2,
            "title": "editor",
            "content": "VS Code with the Vetur extension or WebStorm"
        }
    ]
}
//运行项目
nodemon ./server.js

//在浏览器访问项目
http://localhost:8080/

View the project on the browser side, and the result of the page request is a complete page.
Insert picture description here
It can be seen from a simple simulation case above:

  • Since the page is rendered on the server side, the development work is mainly concentrated on the back end, and the pressure on the server side is great
  • The front and back ends of the website application are completely coupled together, and the front-end development work largely relies on the back-end, and there is not much room for development.
  • Since the client is only responsible for page display, when the page is complex or the network is poor, a long white screen waiting time will appear, and the user experience will be poor

Second, the client renders the page

In order to solve the many shortcomings of traditional server-side rendering, Ajax technology was born. The popularization of Ajax technology makes it possible for the front-end to dynamically obtain data, and also lays the foundation for the separation of front-end and back-end. The basic workflow of SPA applications based on client-side rendering is as follows:

Insert picture description here
In recent years, the three major front-end frameworks Vue, react, and angular are rendering pages on the client side (no cases are provided). The advantages of these frameworks are obvious:

  • Advocate the separation of front and back ends, the back end is responsible for data processing, and the front end is responsible for page rendering
  • The server is only responsible for data processing, which reduces the pressure on the server
  • Reduced page request time and improved user experience
  • Code in separate mode is easier to maintain
  • Avoid the high coupling between the front and back ends, clarify the front and back end development responsibilities, and improve the development efficiency

However, this model has some obvious shortcomings, the most important of which are:

  • Slow loading of the first screen: When this mode is loaded for the first time, it needs to go through the requested page, asynchronously request the data required by the page, and the resources required by the requested page, and then render the requested html page and data on the client side, and finally Presented to the user, causing the first screen to take too long to load.
  • Unable to perform SEO: Because the first time you get an empty page, for the current search engine crawlers, there is no useful information in the page, so it is naturally impossible to extract keywords and index them.

Three, modern server-side rendering page

For some websites from the perspective of corporate benefit and promotion, such as a company's official website, online shopping website, product promotion website, etc., it is necessary to require the website to perform SEO, so the two main flaws of client rendering are fatal. The modern server-side rendering combines the advantages of traditional server-side rendering and client-side rendering to solve this problem. The following is the workflow of this mode:

Insert picture description here
Modern server-side rendering is a combination of client-side rendering and server-side rendering. It is executed once on the server side to achieve server-side rendering (first screen straight out), and executed again on the client side to take over page interaction and core SEO And the problem of slow first screen rendering. Related technologies include Next.js in the React ecosystem, Nuxt.js in the Vue ecosystem, and Angular Universal in the Angular ecosystem. Let's take Nuxt.js of Vue as an example to experience this mode.
Ready to work:

  1. Create a new project
  2. Use yarn init to initialize the project
  3. Install nuxt, axios
  4. The final project directory is as follows:

Insert picture description here
The content of the index.vue file is as follows:

<template>
  <div>
    <h1>{
    
    {
    
     title1 }}</h1>
    <ul>
      <li v-for="item in list" :key="item.id">
        {
    
    {
    
     item.title }}: {
    
    {
    
     item.content }}
      </li>
    </ul>
  </div>
</template>

<script>
import axios from 'axios'
export default {
    
    
  name: "Home",
  //Nuxt.js中的钩子函数,专门用于获取页面服务端渲染的数据
  async asyncData() {
    
    
    const {
    
     data } = await axios({
    
    url: 'http://localhost:3000/data.json'})
    return data;//会将返回数据和Vue本身的data选项进行合并,供页面使用
  }
};
</script>

The content of the default.vue file is as follows:

<template>
  <div>
    <ul>
      <li>
        <!--相当于router-link-->
        <nuxt-link to="/">首页</nuxt-link>
      </li>
      <li>
        <nuxt-link to="/about">关于</nuxt-link>
      </li>
    </ul>
    <!--页面路由视图,相当于router-view-->
    <nuxt></nuxt>
  </div>
</template>

The content of the default.vue file is as follows:

{
    
    
  "title1": "Prerequisites",
  "list": [
    {
    
    
      "id": 1,
      "title": "node",
      "content": "the latest LTS version installed"
    },
    {
    
    
      "id": 2,
      "title": "editor",
      "content": "VS Code with the Vetur extension or WebStorm"
    }
  ]
}

Execute the yarn dev command and access the project in the browser. The page displays the content of index.vue by default. When the route navigation is switched, the page is not refreshed, just like a normal Vue project. This model combines the advantages of Vue.js and solves the shortcomings of Vue.js. At the same time, it also brings a lot of defects:

  • Since the server-side rendering application needs to be in the Node.js server operating environment, the requirements for construction and deployment are higher
  • In a high-traffic environment, a caching strategy is required, and the corresponding load requirements on the server are also increased
  • Because browser-specific code can only be used in certain lifecycle hooks, some external libraries may require special processing to run in server rendering applications, increasing development costs

to sum up

Either way, there are advantages and disadvantages. In the development process, the page rendering mode should be reasonably selected according to specific needs.

  • For the back-end management system, the client-side rendering mode is generally adopted to meet the needs while reducing development costs
  • Websites that have promotion or pursuit of benefits, such as official websites, shopping websites, product promotion websites, etc., generally use modern server rendering mode

Article list

Server-side rendering basic
server-side rendering-Nuxt.js basic
server-side rendering-Nuxt.js comprehensive case
server-side rendering-Nuxt.js comprehensive case release deployment
server-side rendering-Vue SSR construction

Guess you like

Origin blog.csdn.net/weixin_41269811/article/details/112285999