Koa study notes 1

Posted by stephenk on Mon, 21 Feb 2022 07:25:54 +0100

Koa – register login interface implementation notes

1, Construction project

  1. Write a basic app. Note: use must receive a function as middleware
//Import koa module
const Koa=require('koa');
//Create koa instance
const app=new Koa();
//Writing Middleware
   ctx.body+='hello koa'
//Listening port
    console.log('server is running on http://localhost:3000')
  1. Project Optimization: use nodemon tool to automatically restart the service in package Add "dev" under the script of JSON file: "nodemon. / SRC / APP. JS", and then execute npm run dev to start the service.
  2. The function of dotenv module: change the variables in environment variables from Env is loaded into process env. Using dotenv, you can configure environment variables independently of the code.
const dotenv=require('dotenv')
const path=require('path')

//module.exports can use this object to share the members in the module for external use
//When the outside world uses the require() method to import a custom module, the result is module Objects referred to by exports
//Import koa module
const Koa=require('koa');
const {APP_PORT}=require('./config/config.default')
//Create koa instance
const app=new Koa();
//Writing Middleware
   ctx.body='hello koa'
//Listening port
    console.log(`server is running on http://localhost:${APP_PORT}`)

2, Add route

  1. Routing: call different processing functions according to different URL s
const Koa=require('koa');
const Router=require('koa-router')
const {APP_PORT}=require('./config/config.default')

const app=new Koa();
const indexRouter=new Router();
    ctx.body='hello index'
const userRouter=new Router();
    ctx.body='hello user'
//Writing Middleware
//Listening port
    console.log(`server is running on http://localhost:${APP_PORT}`)

3, Koa body

  1. The basic function of KOA body middleware is to help parse the body in http, including json, forms, text, files, etc. Using koa body can replace koa body parser and KOA multer (KOA multer is a middleware for image upload).
//Import koa body
const KoaBody=require('koa-body')
app.use(KoaBody())//Note: be sure to register Koabody before routing!!!

  1. Note: be sure to register the KoaBody before routing

4, Directory structure optimization

  1. In actual projects, the code is often split to increase the readability of the code. Then import the split file as a custom module, which can reduce the coupling of the code. (custom module import: use the module exports object and the require method. The require import refers to the object pointed to by module exports)
    1. Split http service and app business
    2. Split the route and the controller file. Route: parse the URL and distribute it to the corresponding method of the controller; Controller: handles different services.
    3. Split the middleware processing and so on. When writing the code, you can reconstruct the repeated code according to the situation.
      2. For example, index JS is the instance app file, config is the configuration file of environment variables, router is the routing file, controller is the routing control file, service is the database operation file, and main JS is the service startup file.

5, Use of rest client plug-in

  1. Use the rest client plug-in in vscode to send http requests for testing. Create in directory http file or The rest file writes the http request.
### test
POST http://localhost:3000/users/login

POST http://localhost:3000/users/register
Content-Type: application/json


6, Database operation

  1. Sequenize is a promise based node JS ORM database tool. Support Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server.
  2. ORM: object relational mapping. The data table maps a class, the data row (record) in the data table corresponds to an object, the fields in the data table correspond to the attributes of the object, and the operation of the data table corresponds to the methods of the object.
  3. Installation: you need to install serialize and database driver.
    npm install sequelize
    npm install mysql2
  1. Connect to the database: create a serialize instance and pass the connection parameters to the serialize constructor, or connect to a URI. (URI: uniform resource identifier, indicating every available resource on the web)
//Connect database

const {MYSQL_HOST,

const {Sequelize}=require('sequelize')//Deconstruct class
//Pass connection parameters
const sequelize=new Sequelize(MYSQL_DB,MYSQL_USER,MYSQL_PWD,{

//Test whether the connection is successful
//Authjenticate () returns a promise object
    console.log('Database connection succeeded')
    console.log('Database connection failed',err)

  1. Model in serialize: the abstraction of the table in the database will specify the name of the table in the database, the columns and data types it has, and so on.
const {DataTypes}=require('sequelize')
const seq=require('../db/seq')
//Create and define models
const User=seq.define('zd_user',{
    //id will be created automatically
        comment:'Unique user name'

        comment:'Is it an administrator'
  1. The addition, deletion, modification, query and other operations of the database. Write down the next note separately.

7, Encryption

  1. Before saving the password to the database, you need to encrypt the password. Encryption using bcryptjs
  2. Salt encryption:
const crpytPassword = async (ctx, next) => {
    const { password } = ctx.request.body
    //Salt is added and densified to form salt
    const salt = bcryptjs.genSaltSync(1567)
    //Encryption, hash saves the ciphertext
    const hash = bcryptjs.hashSync(password, salt)
    ctx.request.body.password = hash
    await next()

8, User authentication

  1. User authentication: maintain login status after login;
  2. Cookie: when the browser initiates an HTTP request, the server will set the cookie, that is, set cookie. There are two important attributes: name and value in the cookie. The server will fill in the value of the attribute in the cookie completely. After the cookie is sent to the browser, the browser will automatically save it, so that every request sent by the browser in the future will automatically attach the cookie. However, the user name and password are not safe in cookies and are easy to disclose.
  3. Session: the way to maintain a session between the browser and the server. The sessions of different websites and each user are set with time and unique ID (Session ID). The browser accessing the server is the beginning of the session. After successful login, the server will create a Session ID and session end time, and the server will send the Session ID and session end time to the browser, The browser will add the Session ID to the cookie and set the session end time as the validity period of the cookie. The next time you visit the browser, the cookie with Session ID will be sent to the server until the validity period of the cookie expires. The browser will delete the cookie by itself, the session will end and you need to log in again next time.
  4. JSON WEB TOKEN: jwt, after the user logs in the web page for the first time, the server will generate a token. The server does not need to save the token, but only needs to save the ciphertext of the token signature, and then send the token to the browser, which can be stored in the form of cookie or storage.
  5. JWT consists of three parts: header, payload and visa signature. The header part declares what algorithm is used to generate the signature. The payload part is some specific data. The contents of the header and payload parts will be encoded by Base64. The data and password will be calculated by a certain algorithm, and finally the signature information will be obtained. In this way, a complete JWT can be sent to the client.
  6. A cookie is a data carrier that follows every request from http to the server. The main difference between session and Token: the session is saved on the server side, and the browser uses the Session ID for authentication, while the token is saved in the browser, while the server only needs to save the password.

Topics: Javascript Front-end