This is my second article about getting started

Introduction to the

Koa2 is a lightweight framework based on node.js platform, which is built by the original Express team. The core code only has four files, and it does not bind any middleware and supports async functions. Koa2 is very light, free to develop, simple and easy to use. It is suitable for the front end to provide an interface to the back end when developing projects on its own.

The installation

Create a folder. Go to the NPM init -y or YARN init -y command line for quick initialization. Yarn is recommended

Install Koa2

npm i koa

# or

yarn add koa
Copy the code

Koa2 is a scaffold named KOA-Generator, but it has not been updated for a long time on Github, many dependent versions are too low, and Koa2 is relatively easy to build, so it is recommended to build an initial template from scratch.

Koa2 A basic server is very simple, new app.js in the root directory

// app.js
const Koa = require('koa');
const app = new Koa();

app.use(ctx= > {
  ctx.body = 'Hello World';
});

app.listen(3000);
Copy the code

The terminal can start the service by running Node app.js or add commands to package.json:

"scripts": {
    "dev": "node app.js"
}
Copy the code

Open http://localhost:3000/ to see Hello World

It is recommended that you use Nodemon to start app.js so that the service is automatically restarted after each modification of the file and the yarn Add Nodemon-d development dependency is installed

routing

Koa2 is simple and requires an independent installation of the koA-Router module for routing

yarn add koa-router
Copy the code

Simple Routing Application

// app.js
const Koa = require('koa');
// Router introduces a method
const router = require('koa-router') ();const app = new Koa();
const PORT = 3000;

// Receives two parameter routing paths and a callback function
router.get('/'.ctx= > {
  ctx.body = 'Hello World';
});

// Route is enabled through app.use, and other middleware is enabled by app.use
app.use(router.routes(), router.allowedMethods());

app.listen(PORT, () = > {
  console.log(`server is running at http://localhost:${PORT}`)});Copy the code

Route extraction and encapsulation

// app.js
const Koa = require('koa');
const app = new Koa();
const PORT = 3000;
const router = require('./router');

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

app.listen(PORT, () = > {
  console.log(`server is running at http://localhost:${PORT}`)});Copy the code

Router in the root directory

/** * router.js * router.js */
const router = new Router()
const controllers = require('./controllers')

router
  .get('/user', controllers.getUsersList)
  .get('/user/:id', controllers.getUsersById)
  .post('/user', controllers.addUsers)
  .put('/user/:id', controllers.updateUsers)
  .delete('/user/:id', controllers.delUsers)
  
module.exports = router
Copy the code