[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Time:2020-10-26

Write at the beginning

Hello everyone, this is < font color = chocolate > lionlovevue < / font >, basic knowledge determines the thinking of programming. Learning is like sailing against the current. In order to interview, Jin San Yin Si is also slowly accumulating knowledge. GitHub can directly check all the front-end knowledge points, sort out the GitHub portal, and think it’s good to click a star. After a long time of good luck, the offer will eventually come to you and will continue to be updated. In addition, you can also focus on WeChat official account: <font color=chocolate> lion Vue</font>, source code and data will be placed in the future.

Vue Foundation

Global installationvue/cliScaffolding

Run CMD as an administrator and execute the following code:

npm install -g @vue/cli

or

yarn global add @vue/cli

Command line inputvue uiOpen visual interface

Use defaultdefaultto configure

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Open the project with vscode and execute the following command

npm/cnpm run serve

visit: http://localhost : 8080 / check whether the configuration is successful

Custom instruction

Recommended reading: Official Document – custom instructions

In addition to the default built-in instructions for core functions(v-modelandv-show), Vue also allows you to register custom instructions. Note that in vue2.0, the main form of code reuse and abstraction is components. However, in some cases, you still need to do the underlying operations on ordinary DOM elements, and then you will use custom instructions.

assembly

Communication mode of parent-child components

When a parent component passes to a child component, it is used by the child componentprops, and then the parent component:=Binding variables

When a child component passes to a parent component, it uses custom events in the child component, such as:

//Sub component configuration
@click="$emit('patch(xxx)')"
//Parent component configuration
@patch="func"

If it is a cross component relationship rather than a parent-child relationship, use theVuex

slot

The application of slot in component abstract design

The original component can’t embed HTML content, but it can be realized by passing slots through parent-child components

//Parent component
slot="a"
//Sub components
<slot name="a"></slot>

Vuex Basics

<hr/>

Vuex simply means that multiple components share data, but components cannot directly manipulate data. As shown in the figure below, our data is placed in purplestateInside (not indataThe operation data source is from the red partMutationsYes, when is the data yellowActionsIn this case, the user controls the component to triggerActionsFinally, byActonsSubmitCommitNotify to change the data source to complete the update rendering of the component view.
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Installing vuex

npm/cnpm i vuex

Koa2 Foundation

<hr/>

koa-generator

Open CMD as administrator and run the following code to install globally

npm install -g koa-generator

usegit bash , create the project in the folder

koa2 -e project_name

-E means useejs, without sumnodeequally

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Next, execute the install command

cd koa2_learn
npm install

Install & updatefseventspackage

npm install --update-binary

Run app command:

DEBUG=koa2_learn:* npm start

Output after executionnode bin/wwwIt shows that the server has been running

visit http://localhost : 3000 / view page effects

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Let’s seepackage.json, found that the startup script isnpm scriptsIf you want to self start, execute the following command:

npm run dev

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
For the above execution instructions,devandprdMust be usednpm run xxx

At the same time, we areindex.jsPrint it globally and add the following code:
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

staygit bashExecute the following command in

npm run dev

It shows that we have changed the server-side script, and the service can start automatically
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Koa2 Middleware

<hr/>

The picture is from koa2 official, which roughly means that the server accepts the clientRequestAfter some processes on the server side, and thenResponseIt is returned to the browser, and each ring is a middleware. When you come in, you will pass through some middleware, and when you go out, you will also pass through it,This mechanism can make the middleware reference order and code execution order inconsistent.
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Mongoose Basics

<hr/>

Mongodb concept & installation

Mongodb belongs toNon relationalDatabase, andmysqlRelative (MySQL is a relational database)

Not in mongodbtableWatch, onlyCollections

Originally, MySQL was calledrowAnd in mongodb it’s calleddocumentThe original column was calledcloumnAnd now it’s calledfields

Windows 10 installation tutorial:

Recommended reading: installing mongodb on Windows platform

be careful

installInstall MongoDB CompassIf it is not checked, it may take a long time to install. Mongodb compass is a graphical interface management tool, and a graphical interface management tool will be downloaded laterRobo3T

Other options are selected by defaultnextthat will do

Find the two below.exeClick to run it. (the startup service should be the one below)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Check whether the installation is successful

visit: http://127.0.0.1 : 27017 / whether the following interface appears:

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Graphical interface management toolRobo3TInstallation and use

Official website address

Studio windows download address

Robo 3T Download

After entering the installation page, selecteasyVersion, and then choose your favorite theme style, bright or dark style

After entering the graphical interface, create a new oneconnection, select the default port27017, save

Chinese documents of Mongoose

Reference: Chinese document of mongoose 4.5

In the previously configured koa2 folder (mine is koa2_ Learn folder)bashInterface, enter the following command to installmongoose

npm i mongoose

Connect to database

The next step is configuration related

Create a project nameddbsFolder for

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Create a new oneconfig.jsFile, configure the following code

module.exports = {
    dbs: 'mongodb://127.0.0.1:27017/dbs'
}

staydbsCreate a directory namedmodelsFolder for
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Create a new oneperson.jsFile, configure the following code (at this time, the file name corresponds to our “table name”, that isCollections

const mongoose = require('mongoose')

//Creating patterns 
let personSchema = new mongoose.Schema({
    name: String,
    age: Number
})

//Creating models
module.exports = mongoose.model('Person',personSchema)

And then in theapp.jsTo import

const mongoose = require('mongoose')
const dbConfig = require('./dbs/config')

stayapp.jsDefault commentroutesAfter that, add a third line of connection code

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
mongoose.connect(dbConfig.dbs,{
  useNewUrlParser:true
})

The basic configuration is over. Now it’s better to restart the koa service,ctrl+cExit and enter the following command:

npm run dev

The following interface appears, indicating that there is no problem with configuration and the connection is successful!
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
The next step is to try to write an APIusers.jsThe following code is configured in the file

Head import model

//Import model
const Person = require('../dbs/models/person')

Custom API interface

router.post('/addPerson',async function(ctx){
  //Create a new instance of the model
  const person = new Person({
    name: ctx.request.body.name,
    age: ctx.request.body.age
  })
  let code
  try {
    await person.save()
    code=0
  } catch (error) {
    code=-1
  }
  ctx.body={
    code
  }
})

Call the interface.curlIt’s a shell command,-dThe command indicates yespostRequest, followed by the data item, and finally the API interface address

curl -d 'name=chocolate&age=20' http://localhost:3000/users/addPerson

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
At this point, open Robo 3T, refresh our database, and you will find one moredbs
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Check whether there is corresponding write data:
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
The above process basically connects our back-end service with the database. In the future, we only need to apply the previous examples. Next, we will show how to write an API, because the above is to add operations, that is, write operations. Let’s do another read operation.

It’s still thereusers.jsAdd the following code to

//Database read API
router.post('/getPerson',async function(ctx){
  const result = await Person.findOne({name:ctx.request.body.name})
  const results = await Person.find({name:ctx.request.body.name})
  ctx.body = {
    code: 0,
    result,
    results
  }
})

openbash, execute the following command:

curl -d 'name=chocolate' http://localhost:3000/users/getPerson

If found, we will return the JSON data package to prove the API interface implementation
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Finally, the update and delete API are attached to test the validity of the API

//Update API
router.post('/updatePerson',async function(ctx){
  const result = await Person.where({
    name:ctx.request.body.name
  }).update({
    age: ctx.request.body.age
  })
  ctx.body = {
    code: 0,
  }
})
//Remove API
router.post('/removePerson',async function(ctx){
  const result = await Person.where({
    name:ctx.request.body.name
  }).remove()

  ctx.body = {
    code: 0,
  }
})

For more knowledge, please refer to the Chinese document of mongoose 4.5

Redis Foundation

<hr/>

Cookie and Session Introduction

That’s what I’m going to talk about herecookieandsessionThe relevant knowledge points, draw the key point!

Server side program how to identify the state of the client, you know, HTTP is stateless, recommended reading: how to learn the front end, white whoring knowledge

For example, there is a user a who has visited the server program. How does the server program know that the next time it visits is still a?

Therefore, we need to use very important concepts in this area,sessionOf course, this onesessionIt’s not browser,It’s the server’sIt is used to store user information.

So, the server’ssessionHow to keep it on the client?

At this time, we have to introduce another very important concept, thecookie

in summary,cookieandsessionThe relationship between the server and the serversessionTo save the user’s state, and then the client uses thecookieTo savesession, server handlesessionPlanted tocookieAnd then the next time you visit,cookieWill carrysessionAnd thenAchieve an identity authentication effect

Redis concept & installation

Since we know the role of cookies and sessions in the browser and server side, thenredisWhat does it matter?

Think about it. Since it is the function of authentication, it is our server-sidesessionWhere should it exist? Maybe you will want to put it into the server-side storage and memory. This is really a way, no problem, but when the application is very large,sessionWhen the capacity is very large? What about some treasure? At this point, the memory must be insufficient. At this time, a container is needed to store large capacitysessionNow the database is storedredisIt plays a role!

As for the database, I also mentioned abovemongodbCan we also use this?

Although this is also a way, we should consider itRead and write performance issuesBecauseredisyesFast read-write databaseIt is flexible and convenient to usekey-valueType

<hr/>

For better understandingredisHere I quote the official introduction:

  • Remote dictionary server (redis) is a key value storage system written by Salvatore Sanfilippo.
  • Redis is an open source log type, key value database written in ANSI C language, complying with BSD protocol, supporting network, memory based and persistent, and providing API in multiple languages.
  • It is often referred to as a data structure server, because values can be strings, hashes, lists, sets, and sorted sets.

Installation tutorial

Reference: redis installation tutorial

Reference: installation and configuration of redis under Windows

staykoaOfbashInterface, execute the following command to completekoaAndredisConnection of

npm i koa-generic-session koa-redis
redis-server.exe redis.windows.conf

Start redis service

1、 [9980] 21 APR 02:57:05.611 creating server TCP listening socket 127.0.0.1:6379: bind: no error

Solution: run from the command line

redis-cli.exe
127.0.0.1:6379>shutdown

2、 Redis (error) noauth authentication required

127.0.0.1:6379>auth "123456"
127.0.0.1:6379>shutdown
not connected>exit

Then run it againredis-server.exe redis.windows.conf, start successfully!

Reference: redis start error: creating server TCP listening socket 127.0.0.1:6379: bind: no error

Nuxt.js Basics

<hr/>

Nuxt.js It is based on Vue.js The general application framework of the Vue.js Various configurations needed to develop server-side rendering applications.

Based on Vue 2, including Vue router, it supports vuex, Vue server render and Vue meta

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Nuxt.js Workflow

The following figure is from nuxt’s official website, which briefly introduces its workflow

For more information, please refer to the official English document of nuxtjs

Reference: nuxtjs Chinese document
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
From a request from the browser to the final server rendering, the lifecycle of nuxt is as follows:

  • Incoming RequestThe browser sends a request
  • Check whether the server hasnuxtServerInitConfiguration item, if any, this function will be executed, which contains an annotation:Store actionFor operationvuex
  • The next step is middlewaremiddleware, related to routing, do whatever you want
  • Pre validationvalidate()Can cooperate with advanced dynamic routing, do some verification, such as whether to allow jump to a page
  • asyncData() & fetch()Get data, the former is used for renderingvue componentFor Vue components, the latter is usually used to modifyvuex, i.eStoreOf
  • With data and templates, the last step isRenderIt’s rendered in this waySSR

Nuxt.js install

If Vue cli is not installed, install it globally first

npm/cnpm install -g @vue/cli-init
vue init nuxt-community/koa-template nuxt_ Learn (fill in your own file name here)

After installation, execute the following commands in sequence

cd nuxt_learn
npm install # Or yarn
npm install --update-binary
NPM install AJV @ ^ 6
npm run dev

If there is a problem with the installation process network and the error is reported, try it outcnpmperhaps

nrm use cnpm

Eslint version problem:Eslint version needs to be updated
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Solution: execute the following code:

npm install [email protected]^3

After performing the following steps, the last step is to open the service:

npm run dev

There is a problem with the compiled version of Bel:The solution is to upgrade[email protected]reach[email protected]

npm install [email protected] --save-dev

After solving the above problems, the compilation can succeed, but the client still runs and reports errors

The solution is: in thenuxt.config.jsFound ineslint-loadertakectx.isClientChange toctx.ClientIt’s ready to run

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Reference: solve the installation error of Vue init nuxt community / koa template project

After solving the above problems, execute the following instructions:

npm run dev

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
visit: http://localhost : 3000 / the following interface appears, which indicates that the configuration is successful

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Attachment: WeChat official account: Lion front end [nuxt-learn] can get the source code of this section.

Knowledge development

When usingSSRWhen,mountedRender only on the browser side, andDoes not render on the server side: the data requested by the browser through Axios, onlycreatedIt is executed when SSR is turned on.

SSR principle: ① the server will distribute the compiled content (template) (including style, content and data); ② respond the data obtained asynchronously to the browser (hand over the interaction to the browser)

SSR principle in depth

Let’s open the page source code and check it out:
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
After rendering the page on the server side, the HTML on the browser side is divided into several parts, the first is the stylestyleThe second is the template content, such as the < font color = blue > Blue < / font > part in the circle above, and the third one is the data results obtained by the server. For example, the < font color = Red > Red < / font > part in the circle above. Why is the data obtained by the server sent to the browser?
Here we have to think about a < font color = Red > modelHow SSR works< / font >

If you don’t give data, it’s a static HTML templateStatic contentWithout any interaction, where is the interaction completed?

The interaction is completed on the browser side, that is to say, there will be an entrance on the browser side for precompiling, but the page will not be rendered again, because the server side has already rendered the page once.What it does is to create a virtual compilation result (which can be understood as a virtual DOM),Compared with the results from the server, if there is any difference, it will re request the data. In nuxt project, it is a set of files, and there is no specific specification to run in browser side or server side, which is often said by SSRisomorphism, the browser side compiles the virtual DOM, which also depends onvueFile, so there are templates. To compile this DOM, additional data is needed. This data is the data requested before the server-side rendering. If the data is not synchronized in the browser side, the,The result of compiling must be inconsistent with that of server

In conclusion,The data obtained asynchronously on the server side will be synchronized on the browser sideIf the comparison is consistent, the browser will register events for the corresponding DOM node to achieve interaction.

For more information, please refer to the official English document of nuxtjs

Reference: nuxtjs Chinese document

< font color = chocolate > the above is the basic knowledge needed for our project construction, which has been sorted out. Of course, there are still many places that have not been mentioned. Readers can refer to some official documents to supplement more knowledge. Below, we will gradually go deep into the development process records of the whole stack. It is not easy to make, like, collect and comment on, and click one key, three times, and one wave ~ < / font >

Start of project construction

<hr/>

Configuration environment

  • node
  • vue
  • npm
  • webpack
  • nuxt

Create project

npm install -g npx
npx create-nuxt-app loveVueApp

usenpxIt can help us build the project environment more quickly, where you need to create project folderShift + right mouse buttonopenpowershellWindow, execute the above command, and then select the corresponding module according to the following picture:

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
After the installation, you will be prompted to execute the following command:

Here we will execute the instructions of the development environment

cd loveVueApp
npm run dev

Attached are the instructions for the production environment:

cd loveVueApp
npm run build
npm run start

visit: http://localhost : 3000 / there will be a nuxtjs icon, which indicates that the environment has been successfully matched ✿✿ヽ (°▽ °) ノ✿

At this point, thectrl+cQuit current service

Execute the following command to re install it to prevent version problems

npm install  --update-binary

After reloading, run the service again to see if the interface can be opened

npm run dev

Add Babel node processing (using ES6’s import instruction)

After creating our basic project, we also need to make changes to the modules we need.

For example, the first line of code corresponding to the target file:
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Change to the following code

import Koa  from 'koa'

As a result, there will be an error, unable to identify
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Explained abovenuxtjsWe can use it directlyimportYes, but we didn’t deal with this when we used the official scaffoldbugYes. Here’s why this problem occurs

When we use commandsnpm run devIn fact, it is usednpmOfscriptAs shown in the figure below:

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

It can be seen that it has been usednode, and does not supportimportOperation, the above is because of the use ofbabelIt has been treated and used in the official scaffold herenodeTo start the service without passing throughbabelProcessing, so it’s not recognizedimportYes.

Solve the above problems

The reason mentioned above is that there is no such thingbabelTo handle and execute the service procedures, you can add it yourself. The details are as follows:

staydevandstartAdd after--exec babel-node

Or simply use the following code to override yourscripts

"scripts": {
    "dev": "cross-env NODE_ENV=development nodemon server/index.js --watch server --exec babel-node",
    "build": "nuxt build",
    "start": "cross-env NODE_ENV=production node server/index.js --exec babel-node",
    "generate": "nuxt generate"
  },

Then, create one in the root directory.babelrcAnd then assign it a set of instructions

{
    "presets":["es2015"]
}

If you have the code, you need to install the plug-in and execute the following command

npm install babel-preset-es2015
npm install babel-cli -S

All right, here we arebabel-nodeAfter that, we can start the service program, which we usually useES6Grammar

npm run dev

visit: http://localhost : 3000 / there will be a nuxtjs icon, which indicates that the environment has been successfully matched ✿✿ヽ (°▽ °) ノ✿

Solve the problem of compilation errors caused by sass

This problem is still caused by the scaffold. The solution is to install several plug-ins. The execution command is as follows:

npm install sass-loader node-sass

PS: there may be the followingwarn

NPM install eslint @ ^ (version number) // (Note: This is executed when the corresponding warn appears)

This is my warning, so follow the example and execute the following order
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

npm install [email protected]^1.3.0 [email protected]>= 3.1.0

Installation of auxiliary tools

  • MongoDB
  • redis
  • Robo 3T

(the installation tutorial is introduced in the basic part above. You can go back to the corresponding module ↑)

Common instructions of remote warehouse

  • View branch:git branch
  • View the branches of the project (both local and remote) git branch -a
  • Create branch:git branch <name>
  • Switch branch:git checkout <name>
  • Create + switch branch:git checkout -b <name>
  • Merge a branch to the current branch:git merge <name>
  • Submit git commit – M ‘Introduction’
  • git push -u origin master

Home page development

requirement analysis

  • Template design (solve reuse problem)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

  • Component design (how to split components)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
How to save network requests?

In addition, when data is obtained asynchronously, there will beFlash, affect the user experience and waste a network request. The solution is when the browser to request the server, when the browser to request documents, the serveripAlready know, at that time, you can get the corresponding city, and immediately return the data to the browser. The way is throughvuexTo synchronize the state, and then through theSSRData can be obtained by asynchronous requests.

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Similar to the flow chart above, you can also use thevuexTo do it
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
It belongs to the static module. It doesn’t need us to get data asynchronouslySSRIt’s OK to issue it once.

  • Data structure design (data and component dependent)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
POIs table City recommendation database
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

  • Interface design (corresponding to data structure)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Home page development header city positioning service design

according toHeaderIn terms of layout, we are incomponentsCreate the following folders and files under the folderREADME

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Import CSS and opennuxt.config.jsConfigure
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Project development may encounter problems

<hr/>

< font color = Red > important reminder! </font>

This article can be detailed overview of the place is limited, so the following will focus on the main part, the rest of the reference source, has been open, the development process according to the branch, and then merge intomasterbranch

Warehouse gate (stamp)

CollectionstarA wave, ✿ヽヽノ✿

About the configuration of SMTP service function in the project

As shown in the figure below, we first log in to our QQ, open our mailbox, and then open the following two services
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
stayserver/dbs/config.jsThe file can be changed to your own authorization key and mailbox
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Introducing Mongoose

npm install mongoose

to configureusersInterface

npm install koa-router koa-redis nodemailer

to configureaxios

npm install axios

to configurepassport

npm install koa-passport passport-local

About the login registration interface in the project

passport It’s in the bagisAuthenticated()Method, so it is not defined in the document source code.

passport The user’s information object will be placed in thesessionGo inside the object, that ispassportWill be stored insessionFor example, if it is in login status, the session will havepassport, andpassportThere will beuser

//Determine whether it is login status
  if (ctx.isAuthenticated()) {
    const {username, email} = ctx.session.passport.user
    ctx.body={
      user:username,
      email
    }
  }
  • users.js

Server folder index.js Load the relevant package in the file

import mongoose from 'mongoose'
import bodyParser from 'koa-bodyparser'
import session from 'koa-generic-session'
import Redis from 'koa-redis'
import json from 'koa-json'
import dbConfig from './dbs/config'
import passport from './interface/utils/passport'
import users from './interface/users'
import geo from './interface/geo'
import search from './interface/search'
import categroy from './interface/categroy'
import cart from './interface/cart'

Load instruction:

npm install mongoose koa-bodyparser koa-generic-session koa-redis koa-json

Cannot read property ‘post’ of undefined

When I registered with the module, I sent a verification code and then reported this error. At first, I thought that the interface was written incorrectly, and I also tested it. The original reason is thataxiosNot innuxtConfiguration in scaffold

Cannot read property 'name' of undefined

nuxt.config.jsThe file is configured as follows:

module.exports = {
  modules: [
    '@nuxtjs/axios',
  ],

  axios: {
    // proxyHeaders: false
  }
}

After solving the problem, the verification code is sent. As a result, an e-mail is sent to ✿✿ヽ (°▽ °) ノ✿
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

About win10 redis reporting error permission denied

It is also the registration page. After we register, we click agree to the agreement and register. If we find that we can’t jump to the login interface, we will be promptedRegisteredAfter reading it for a long time, it was prompted that there was a service error. As soon as the redis command window was opened, this error was reported. It turned out to be the default settingRead only, not writeTo solve the problem ✿ ✿ ヽ (° ▽ °) ✿

Solution: go to the RDB file of redis to view the file properties and increase the write permission
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
Reference: redis’s hole in Windows

About win10 mongodb importing. Bat file

The following instructions were used on the Internet, but I still failed to import them. They said that there was no such instruction, but the database was imported beforeusers

mongoimport -d student -c areas areas.dat

So I opened itStudio 3TTry to import it. It’s a success

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)
My approach is to go straight to the one on the leftCollectionsRight click to select the folderAddOperation, and then import.datFile, but there will be a suffix after the import, so I renamed it. Although it seems a bit silly, but it is also solved ✿✿ヽノ✿
[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

About geo service interface signature

http://cp-tools.cn/sign

Location service and geo bug resolution of switching cities

Positioning in the citygeoThere are two * * scorched by the flames, which made me feel very worried. Finally, I found a solution. I wrote this module, and I recorded the “

< font color = Red > ① error classic mode for store / is degraded and will be removed in nuxt 3. < / font > 1

<font color=red>② Error occurred when calling nuxtServerInit: socket hang up</font>

YesFirst questionThe reason for this error is that the original vuex programming has been removed from the nuxt3 version. The error code is as follows:

The solution is as follows: each. JS file in the store directory will be converted into a sub module named by the status tree (index is the root module, of course).

(the following code is valid for pro testing, and it can cover your code directly)

First of all, the directory structure is modified. There is no need to add another one for the latest versionmodelsFolder.

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

index.jsDocument:

export const actions = {
  async nuxtServerInit({
    commit
  },{req,app}) {
    const {status,data: {province,city}} = await app.$axios.get('/geo/getPosition')
    commit('geo/setPosition',status===200?{city,province}:{city:'',province:''})      
    const {status:status2, data: {menu}} = await app.$axios.get('/geo/menu')
    commit('home/setMenu',status2===200?menu:[])
  }
}

geo.jsThe document does not need to be modified

YesThe second questionMostly because you wrote itgeoThe related interface is not inserve/index.jsFor import and configuration use (this is why I am)

import geo from './utils/geo'
app.use(geo.routes()).use(geo.allowedMethods())

The specific import location is as follows:

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

[Vue family barrel + SSR + koa2 full stack development imitation beauty group] project construction process integrated learning directory (under continuous update)

Reference: meituan project positioning service and city switching 5

Reference: Using SSR in nuxtjs to develop the front-end vuex request background

On the number of search box requests

Of course, we can’t request the interface once without entering a character, so we need to make a delay function

npm install lodash

Lead into storage

import _ from 'lodash'

Optimization and implementation of switching City module

First of all, it is clear which one of the cities to be requested is the province (Level 1). In this case, you can use SSR for server-side rendering. After loading the page, you can also load it. But here, you can directly use the mouted life function in Vue to complete the Axios request here

mounted: async function() {
    let self = this;
    let {
      status,
      data: { province }
    } = await self.$axios.get("/geo/province");
    if (status === 200) {
      self.province = province.map(item => {
        return {
          value: item.id,
          label: item.name
        };
      });
    }
  }

Linkage logic, use watch to monitor what province the user has selected

//Monitor the value of pvalue. When the province changes, the selected cities will also change (linkage)
  watch:{
    pvalue:async function(newPvalue){
      let self=this;
      let {status,data:{city}}=await self.$axios.get(`/geo/province/${newPvalue}`)
      if(status===200){
        self.city=city.map(item=>{
          return {
            value:item.id,
            label:item.name
          }
        })
        self.cvalue=''
      }
    }
  },

Pay attention to the design of the select drop-down box, if you don’t set itlabelIt’s still showingvalueBut if you set thelabelThat’s what the input box showslabelBut youv-modelIt’s still youvalueSo copying in a province will alsoidAssign tovalueSo the parameters are correct!
Can the two-level linkage, three-level linkage still be difficult? After all, now you just need to focus on logical code, andDOMThe structure of the e-ui has been casually completed, leaving only the code that you associate with them

Reference: meituan project – switching cities 7

Mining knowledge points through projects

What is CTX in koa2?

To try to understand, use console.log Output it

{ request:
   { method: 'GET',
     url: '/',
     header:
      { host: 'localhost:3000',
        connection: 'keep-alive',
        'cache-control': 'max-age=0',
        'upgrade-insecure-requests': '1',
        'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',
        accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'accept-encoding': 'gzip, deflate, sdch, br',
        'accept-language': 'zh-CN,zh;q=0.8' } },
  response:
   { status: 200,
     message: 'OK',
     header:
      { 'content-type': 'text/plain; charset=utf-8',
        'content-length': '25' } },
  app: { subdomainOffset: 2, proxy: false, env: 'development' },
  originalUrl: '/',
  req: '<original node req>',
  res: '<original node res>',
  socket: '<original node socket>' 
}

It can be seen that it mainly includesrequestandresponseTwo parts.

< div > CTX is the abbreviation of context, which is generally called context in Chinese. This noun, which is common in all languages, can be understood as the communication environment between request and response. Therefore, both of them are encapsulated in the CTX object in KOA. The explanation in koa’s official documents is for convenience, ctx.req=ctx .request, ctx.res=ctx . response, similar to the soft connection in Linux system? The final execution is still the request and response objects

< div > body is the response body of HTTP protocol, and header is the response header ctx.body = ctx.res.body = ctx.response.body </div>

Koa provides a context object that represents the context of a conversation (including HTTP requests and HTTP replies). By processing this object, you can control what is returned to the user.

Context.response.bodyProperty is what is sent to the user.

const Koa = require('koa');
const app = new Koa();

const main = ctx => {
  ctx.response.body = 'Hello World';
};

app.use(main);
app.listen(3000);

In the above code, the main function is used to set thectx.response.body。 Then, use theapp.useMethod to load the main function.

As you might have guessed, ctx.response Stands for HTTP response. similarly, ctx.request Stands for HTTP request.

Run this demo to access http://127.0.0.1 : 3000, you can see “Hello world” now.

Reference: what is CTX in koa2?

Query and querystring in koa2

In koa, get request gets the request data. The query method and querystring method in the request object return the formatted parameters, and the querystring method returns the request string.

How does koa2 get the route parameters of get mode, such as XXX? Name = 123 gets the name value

ctx.request.query
// => {name: '123'}
ctx.query
// => {name: '123'}

ctx.requestyesKoaRequest object. It can be done throughquerystringGet thequeryString, byqueryGet the formatted parameters.
ctx.queryyesroute.queryAlias of.

Read: nuxt – nuxtserverinit & store processing before page rendering & Context

Koa2 uses passport authority authentication Middleware

Reference: koa2 uses passport authority authentication middleware

serialization and deserialization

For more information, please refer to: learn about passport serialization and deserialization

Therefore, the name of speculation is to convert structured objects into byte sequences, and vice versa is called deserialization.

Why serialize and deserialize?

The object in memory is structured. When you need to transfer this object in the network, or save it to a file or database, you need to serialize it into a byte stream for easy processing.

On the other hand, after the transfer, or when it is read from files and databases, it is necessary to rebuild and restore the original objects.

The analogy is, for example, when we make a phone call, wires can’t transmit sound directly. We need to convert sound into current, and then convert current into sound in the past.

Why utils/ axios.js To create an instance

For reference: nuxt.js Official Chinese documents

If you use thenode_modulesMediumaxiosAnd use theaxios.interceptorsAn interceptor is added to process the request or response data to ensure that theaxios.createCreate an instance before using it. Otherwise, if you refresh the page request server many times, the server-side rendering will add interceptors repeatedly, resulting in data processing errors.

import axios from 'axios'
const myaxios = axios.create({
  // ...
})
myaxios.interceptors.response.use(function (response) {
  return response.data
}, function (error) {
  // ...
})

ending

If there are any defects in this article that need to be modified, please mention it. Thank you for your contribution!

Welcome to WeChat official account: Lion Vue

Thank you for your support! ✿✿ヽ(°▽°)ノ✿

Learning is like sailing against the water, and if you don't go forward, you will go back