node.js (koa2)

installation

npm install koa-generator -g
复制代码

New koa2-test program

Koa2 koa2-test
复制代码

Enter koa2-test project, and then execute install

npm install
复制代码

Install cross-env

npm install cross-env --save-dev
复制代码

Modify package.json

    "dev": "cross-env NODE_ENV=dev ./node_modules/.bin/nodemon bin/www",
    "prd": "cross-env NODE_ENV=production pm2 start bin/www",
复制代码

Run npm run dev

routing

routes routing directory is a directory, create a new file login.js

Write to imitate users.js

const router = require('koa-router')()

router.prefix('/login')

router.get('/', function (ctx, next) {
  ctx.body = 'this is a login response!'
})

router.get('/next', function (ctx, next) {
  ctx.body = 'this is a login/next response'
})

module.exports = router

复制代码

In the introduction app.js

const login = require('./routes/login')

复制代码
app.use(login.routes(), login.allowedMethods())
复制代码

At this time bin / www.js in the default port number is 3000, then the browser to http: // localhost: 3000 / login

log in

installation

npm i koa-generic-session koa-redis redis --save
复制代码

In app.js, the write before the route, if no local computer redis installed, will have to install

const session = require('koa-generic-session')
const redisStore = require('koa-redis')
----------------------------------------------
app.keys = ['hello123456*']
app.use(session({
  cookie: {
    path: '/',
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000
  },
  store: redisStore({
    all: '127.0.0.1:6379'
  })
}))

复制代码

Test session, in the login.js

router.get('/session-test', async function(ctx, next){
  if(ctx.session.viewCount == null){
    ctx.session.viewCount = 0
  }
  ctx.session.viewCount++

  ctx.body = {
    errno: 0,
    viewCount: ctx.session.viewCount
  }
})
复制代码

turn on

http://localhost:3000/login/session-test
复制代码

Display, plus a refresh, change browser session on reset

session a success

interface

installation

npm i mysql xss --save
复制代码

Returns the data model interface

class BaseModel{
    constructor(data,message){
        if(typeof data === 'string'){
            this.message = data
            data = null
            message = null
        }
        if(data){
            this.data = data
        }
        if(message){
            this.message = message
        }
    }
}

class SuccessModel extends BaseModel{
    constructor(data,message){
        super(data,message)
        this.errno = 0
    }
}

class ErrorModel extends BaseModel{
    constructor(data,message){
        super(data,message)
        this.errno = -1
    }
}

module.exports = {
    SuccessModel,
    ErrorModel
}
复制代码

The basic configuration of database connection, create a new folder conf, conf folder New db.js, the local computer to install mysql database, I use visualization tools operating mysql database (mysql official recommended)

const env = process.env.NODE_ENV //环境变量

// 配置
let MYSQL_CONF
let REDIS_CONF

if(env === 'dev'){
    // mysql
    MYSQL_CONF = {
        host: 'localhost',
        port: '3306', //默认端口号
        user: 'root',
        password: '123456', //密码
        database: 'myblog' //你的数据库名字
    }
    // redis
    REDIS_CONF ={
        port: '6379',   //默认端口号
        host: '127.0.0.1'
    }
}
// 由于都是在本地,没有上线,所以 env 没有起到作用,做个提示
if(env === 'production'){
    // mysql
    MYSQL_CONF = {
        host: 'localhost',
        port: '3306',
        user: 'root',
        password: '123456',
        database: 'myblog'
    }
    // redis
    REDIS_CONF ={
        port: '6379',
        host: '127.0.0.1'
    }
}

module.exports = {
    MYSQL_CONF,
    REDIS_CONF
}
复制代码

The modified app.js redis redistribute

const { REDIS_CONF } = require('./conf/db')
复制代码

modify

store: redisStore({
    all: `${REDIS_CONF.host}:${REDIS_CONF.port}`
  })
复制代码

Create a new folder db, db folder New mysql.js, used to package mysql query that returns a promise

const mysql  = require('mysql')
const {MYSQL_CONF} = require('../conf/db')

// 创建连接对象
const con = mysql.createConnection(MYSQL_CONF)

// 连接
con.connect();

// 创建同意执行sql语句的函数
function exec(sql){
    const promise = new Promise((resolve,reject) => {
        con.query(sql,(err,result)=>{
            if(err){
                reject(err)
                return
            }
            resolve(result)
        })
    })
    return promise
}

module.exports = {
    exec,
    escape: mysql.escape
}

复制代码

New controller folder, inside the new user.js

const {exec, escape} = require('../db/mysql')

const login = async (username, password)=>{
    username = escape(username)
    password = escape(password)
    const sql = `select username, realname from users where username=${username} and password = ${password}`
    const rows = await exec(sql)
    return rows[0] || {}

}
module.exports = {
    login
}
复制代码

Add in the database

Added sql statement

insert into users(username,`password`,realname) values('wangwu','123','王五')
复制代码

Use postman inquiry

The success of
the overall process is: routes / login.js write routing file --- "controller / user.js do mysql query operation ---" db / mysql.js connected database operations --- "conf / db.js database the basic configuration

Reproduced in: https: //juejin.im/post/5d087607f265da1baf7cedc5

Guess you like

Origin blog.csdn.net/weixin_33989058/article/details/93179249