EggJS+MySQL (mysql2+egg-sequelize+egg-cors) In fact, I learned Node framework route: Express → Koa → Egg. Today, I will record the process of learning Koa results.

1. Introduction

1.1 Koa official website document

The following is an excerpt from the official website:

Koa is a new Web framework, built by the same people behind Express, that aims to be a smaller, more expressive, and more robust cornerstone of web application and API development. By making use of async functions, Koa helps you discard callback functions and greatly enhances error handling. Koa does not bundle any middleware, but rather provides an elegant way to help you write server-side applications quickly and happily.

1.2 Source code for this example

2. Start

2.1 Quick Initialization

Koa relies on Node V7.6.0 or ES2015 and later and async method support.

Global install KOA2 Generator scaffolding: NPM I-g KOA-generator create KOA2 project: KOA2 project nameCopy the code

2.2 Installing plug-ins and configuring them

2.2.1 Introduction to plug-ins

Mongodb Basic library for mongodb operations. Koa2-cors Enables cross-domain access.

2.2.2 installation

npm install mongodb koa2-cors --save

2.2.3 Configuring installed plug-ins

After installing the plug-in, you need to configure it in app.js.

const Koa = require('koa')
const app = new Koa()
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const router = require('./app/routes')

// Handle cross-domain
app.use(cors());
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Origin"."*")
  await next()
})
// The middleware can return the parameters of the POST request in JSON format
app.use(bodyParser());

app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000.() = > {
  console.log(`Listening: http://localhost:3000/`)});Copy the code

3. Write sample code

The following is the directory structure of the project, with most of the logical code inapp/controllers. This example is mainly to achieve a user information to add, delete, change and check.

3.1 Basic Configuration Items

The basic global constants for the project are defined in config/index.js

let app  = {
  url :'mongodb://localhost:27017/'.dbName : 'koa_blog'
}
module.exports = app
Copy the code

3.2 packaging mongo

Package mongodb in config/db.js

const Config = require('./index')
const MongoDB = require('mongodb')
const MongoClient = require('mongodb').MongoClient;
const ObjectID = MongoDB.ObjectID;

class DB{
  constructor(ele){
    // See the source code at......
  }

  static getInstance(){
    // See the source code at......
  }

  connect(){
    //nodejs connects to the database
    // See the source code at......
  }
  / / new
  insert(collectionName,data){
    // See the source code at......
  }
  / / update
  update(collectionName, json1, json2) {
    // See the source code at......
  }
  / / delete
  delete(collectionName,condition){
    // See the source code at......
  }
  / / query
  find(collectionName, json1, json2, json3) {
    // See the source code at......
  }

  // The fixed notation is used to get the _id subscript
  getObjectID(id){
    // See the source code at......}}module.exports =  DB.getInstance()
Copy the code

3.3 the Controller layer

Controllers /users.js User business logic

const DB = require('.. /.. /config/db')

// Query all users
const list = async ctx => {
  const {page,pageSize} = ctx.request.query
  const data = await DB.find('user',{},{},{page,pageSize})
  let feedback
  try {
    feedback = {code:200.msg:'success',data}
  }catch (e){
    console.log(e);
    feedback = {code:500.msg:'server error'}
  }
  ctx.body = feedback
}

// Add a user
const addUser = async ctx => {
  const {username,nickname,age,sex} = ctx.request.body
  await DB.insert('user',{username,nickname,age,sex})
  let feedback
  try {
    feedback = {code:200.msg:'add success'}}catch (e) {
    console.log(e);
    feedback = {code:500.msg:'server error'}
  }
  ctx.body = feedback
}

// Edit the user
const editUser = async ctx => {
  const {_id,username,nickname,age,sex} = ctx.request.body
  await DB.update('user', {'_id': DB.getObjectID(_id)},{username,nickname,age,sex})
  let feedback
  try {
    feedback = {code:200.msg:'edit success'}}catch (e) {
    console.log(e);
    feedback = {code:500.msg:'server error'}
  }
  ctx.body = feedback
}

// Delete the user
const deleteUser = async ctx => {
  const {_id} = ctx.request.query._id
  await DB.delete('user',_id)
  let feedback
  try {
    feedback = {code:200.msg:'delete success'}}catch (e) {
    console.log(e);
    feedback = {code:500.msg:'server error'}
  }
  ctx.body = feedback
}

module.exports = { list, addUser, editUser, deleteUser }
Copy the code

Controllers /index.js is used to expose all action classes under the Controller layer

const users = require('./users')
module.exports = { users }
Copy the code

3.4 the routing layer

Finally, write the interface in app/routes/index.js

const router = require('koa-router') ()const { users } = require('.. /controllers')

// User operation
router.get('/users/list',users.list)
router.post('/users/add',users.addUser)
router.put('/users/edit',users.editUser)
router.delete('/users/delete',users.deleteUser)

module.exports = router
Copy the code

4. Run the project

Open console: Nodeapp.js, you can see: Listening: http://localhost:3000/


Creation is not easy, give a thumbs up and attention, thank you *