Server side rendering basics

An overview of the

With the development of front-end technology stack, front-end frameworks based on client rendering appear. SPA (single-page application) constructed by such frameworks has the advantages of user experience number, good rendering performance and high maintainability, but there are also some defects: In order to solve these two defects, it is proposed to execute front-end framework code on the server side to generate web content, and then return it to the client, and the client only displays itCopy the code

What is rendering

To concatenate data with a templateCopy the code

Traditional server-side rendering

npm i express // Node creates the serverUsing nodemon index. Js// Start the server-side code
npm i art-template // a third party template engine
Copy the code

Traditional server rendering has a lot to lose as web pages become more responsible

  • The front and back end code is completely coupled, which is not conducive to development and maintenance
  • There’s not enough room on the front end
  • The server is under heavy pressure
  • Average user experience

Client-side rendering

The front end is more independent, not limited to back-end disadvantages

  • The first screen rendering is slow
  • Is not conducive to SEO

Why does the client render the first screen slowly

  • CSR: Client rendering

Why client-side rendering is bad for SEO

  • SEO site ranking in search engines

The client page searches for an empty HTML page

Modern server-side rendering

That is, isomorphic rendering = back-end rendering + front-end rendering

  • Based on React, Vue and other frameworks, the combination of client-side rendering and server-side rendering
    • Execute once on the server side for server-side rendering (first screen straight out)
    • This is done again on the client side to take over the page interaction
  • The core addresses SEO and slow first screen rendering
  • It has the advantages of traditional server-side rendering as well as client-side rendering

Nuxt.js of Vue Ecology is taken as an example to demonstrate the application of isomorphic rendering

npm init -y
npm i nuxt
npm run dev // Start the project after creating it
// Nuxt creates a route for the pages folder by default. The default route is index.vue
// localhost:3000/about
Copy the code

Isomorphic rendering for SPA applications

Problems with isomorphic rendering applications

  • Development conditions are limited
    • Browser-specific code can only be used in certain lifecycle hook functions;
    • Some external extension libraries need to be processed before running in server-side rendering applications;
    • You can no longer manipulate the DOM during server-side rendering
    • Some code operations need to be context-specific
  • More requirements for design build setup and deployment
    • Client-side rendering
      • You simply build the client application, which can be deployed on any Web server
    • Isomorphism rendering
      • Two ends need to be built and can only be deployed in Node.js Server
  • More server-side load
    • Rendering a full application in Node takes a lot of CPU resources compared to servers that simply serve static files
    • If the application is used in a high-traffic environment, you need to prepare server loads
    • More server-side rendering optimization work is required
  • Suggestions for using server-side rendering
    • Does first-screen rendering speed really matter?
    • Do you really need SEO?

NuxtJS basis

NuxtJS introduction

  • A third-party open source server rendering application framework based on vue. js ecosystem
  • It allows us to easily build homogeneous applications using vue.js technology stack
  • Nuxt.js is primarily concerned with UI rendering for applications
  • It initializes the basic structural code of the new project
  • Official website: [link] (zh.nuxtjs.org/)
  • GitHub Repository [link to code] (github.com/nuxt/nuxt.j…

Asynchronous data -asyncData

  • Zh.nuxtjs.org/guide/async…
  • Basic usage
    • It will return data to the data fusion component along with the data method returned by asyncData
    • Call timing: during server rendering and before client routing updates
  • Matters needing attention
    • Can only be used in page components
    • There is no this because it is called before the component is initialized

If you want dynamic page content to benefit SEO or speed up the first screen rendering, send a request to fetch data in asyncData

    async asyncData () {
        console.log('asyncData')
        console.log(this)
        const res = await axios({
            method: 'GET'.url: 'http://localhost:3000/data.json'
        })
        return res.data
    }
Copy the code

If the data is non-asynchronous or common, it can be initialized to data

Asynchronous data-context objects

    async asyncData (context) {
        console.log(context, 'Context object, self-naming')
        console.log(this)
        const res = await axios({
            method: 'GET'.url: 'http://localhost:3000/data.json'
        })
        const id = Number.parseInt(context.params.id)
        // The element that gets asynchronous data uses a context object, not this
        return{article: data. Posts. Find (item= > item.id === id)
        }
    }
Copy the code

NuxtJS integrated case

Case introduced

  • Case name: RealWorld
  • An open source learning project that helps developers quickly learn new skills
  • GitHub Repository: github.com/gothinkster…
  • Online example: HTTPS :demo.realworld. IO /#/
Learning harvest
  • Master the development of isomorphic rendering applications using Nuxt.js
  • Enhance the practical ability of vue.js
  • Master the common function processing in isomorphic rendering application
    • User status Management
    • Page access permission processing
    • SEO optimization
  • Master the publishing and deployment of isomorphic rendering applications

The project of actual combat

    mkdir nameFile 
    npm i nuxt
    npm init -y
    // Modify the script configuration in scripts in package.json
    // "dev": "nuxt"Create a Pages file in the root directory and initialize the route Ctrl + C Ctrl + V...... npm i axios npm i js-cookie npm i cookieparser// A lightweight third-party library for formatting time
    npm install dayjs --save
    // Markdown format to HTML third party package
    npm install markdown-it --save
Copy the code

Demo Project Address

https://github.com/honey111/LG-HW-HomeWork/tree/master/part3-3/code/realworld-nuxtjs
Copy the code

Nuxt.js release deployment package

  • Zh.nuxtjs.org/guide/comma…
// Configure it in package.json
  "scripts": {
    "dev": "nuxt"."build": "nuxt build"."start": "nuxt start"
  },
  
  npm run dev
  // The project can be accessed locally after startup
Copy the code

Publish Deployment – The easiest way to deploy

  • Configure Host + Port
    <! -- nuxt.config.js --> server: {host: '0.0.0.0'.port: 3000
    },
    Copy the code
  • Package project files:. Nuxt, static, nuxt.config.js, package.json, and package-lock.json are compressed into a package
  • Upload the distribution package to the server

First connect to the server create a folder after successful connection

mkdir realworld-nuxtjs
cd realworld-nuxtjs
pwd  // Copy the current directory
exit Exit the server or re-open a window
scp realworld-nuxtjs.zip ubuntu@42.192. * * *. * * * :/home/ubuntu/realworld-nuxtjs
Copy the code
  • Unpack the
SSH Connection to the server CD realworld-nuxtjs unzip realworld-nuxtjs.zipCopy the code
  • Install dependencies
npm i
Copy the code
  • Start the service
npm run start
Copy the code

After the startup, enter the public IP address and port number in the browser

Buying a server

Tencent cloud bought a server for a year, really expensive

Connecting to the server

ssh ubuntu@42.192. * * *. * * *// Account name@public IPEnter the password to log in to PWD// View the current directory of the foldercd .. /// Go to the root directory
exit // Exit the server
Copy the code

Nodejs is installed on the server

Log in to the server at echo $PATH// View environment variables

// The first way to download
wget -qO- https:/ / raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash / / download a script that will automatically add environment variable, but I didn't automatically add this step
nvm --version  // # re-connect to SSH after exit
echo $PATH // # check the environment variables
nvm install --lts // # install node.js LTS
// The above steps failed, the environment variable can not be added, I don't know why


// Then change a download mode, directly download the compressed package decompress, manually add environment variables
// The second way
wget https:/ / npm.taobao.org/mirrors/node/v10.6.0/node-v10.6.0-linux-x64.tar.xz

tar -xvf node-v106.. 0-linux-x64.tar.xz  // tar -xvf + Name of the node version that was installed
mv node-v106.. 0-linux-x64 node  // Change the node installation directory name (folder name)Ln -s /root/+ The file name changed in the third step +/bin/node /usr/sbin/node   // You can obtain the path through PWD // create a soft connectionLn -s /root/+ The file name changed in the third step +/bin/npm /usr/sbin/npm  
node -v
npm -v

// Since my account is a normal account, I need to temporarily enable root permission
// After logging in to a common account, you can enter it directly
sudo passwd root // Change the root password. Run this command when the root password is not knownReset the root password// How a common user obtains root permissionSu Enter the root passwordCopy the code

Start the project using PM2

npm i pm2 -g // If it is installed, start it directly
// Create a soft connection manually if the pm2 command cannot be found
pm2 start npm -- start // Start the project
pm2 stop id // End the project
Copy the code

After PM2 starts the project, enter the public IP address of the server and the port number you set in nuxt.config.js to access the project

Nice, we’re done. We’re happy

It is the first time for me to write a summary article of my study. Please forgive me if I am not good enough. If there is anything unclear, I can comment on it or point out the problems I have written. What makes me bald in this module is the server construction. I am so unfamiliar with this module that I have never touched the server before. I worked out everything from the server purchase to the configuration, thanks to my colleagues, teachers and students in the training camp for their patient guidance. And my little snow teacher to me, yes, I can drag too. But at least we’re on to the next stage. After this period of learning to learn a lot, good habits of writing code, as well as some very cool tips, as for what tips, of course, is only can not be explained, envy it.

I’m a stupid bird, but I’m already flying. Come on, hao!

Article content output source: pull hook education big front-end high salary training camp.