Build a Node application practice based on KOA2

Serious front-end development took the first step of the full stack, recording a koA2 build a background application.

Environment set up

The previous installation is complete

  • The node v10.16.0
  • NPM 6.9.0

Project preparation

Create a project folder
mkdir node-koa2-app

# enter folder
cd node-koa2-app

# NPM initialization
npm init -y

Copy the code

First experience of KOA service

Install the KOA frame

npm i koa -S
Copy the code

Create an app.js file and try Hello World!

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

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

app.listen(3000);
Copy the code

Visit http://localhost:3000 to see Hello World! It’s really easy.

Once again, the access is a finished HTML

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

app.use(async (ctx, next) => {
    await next();
    ctx.response.type = 'text/html';
    ctx.response.body = '< h1 > Hello World! ';
});

app.listen(3000, () => {
    console.log('listening server http://localhost:3000');
});
app.listen(3001, () => {
    console.log('listening server http://localhost:3001');
});
Copy the code

The middleware

A Koa application is an object containing a set of middleware functions that are organized and executed in a stack-like fashion.

ctx

CTX is a Context that encapsulates the Node’s request and response objects into a single object. Context also acts as a proxy for some commonly used properties or methods within Koa, enabling us to obtain them directly through CTX. For example, ctx.request.url can be written as ctx.url. In addition, Koa also specifies a storage space for the middleware, CTX.state. State allows you to store some data, such as user data, version information, etc.

next

This is a cascading approach where when one middleware calls next(), the function pauses and passes control to the next middleware defined. When there are no more middleware executions downstream, the stack expands and each middleware resumes performing its upstream behavior.

// const Koa = require('koa') const app = new Koa() // Record execution time app.use(async (CTX, next) => {let stime = new Date().getTime()
  console.log('Start time'+stime);
  await next()
  let etime = new Date().getTime()
  ctx.response.type = 'text/html'
  ctx.response.body = '< h1 > Hello World! '
  console.log('End time'+etime); Console. log(' Request address:${ctx.path}, response time:${etime - stime}ms`)
});

app.use(async (ctx, next) => {
  console.log('Middleware 1 doSoming');
  await next();
  console.log('Middleware 1 end');
})

app.use(async (ctx, next) => {
  console.log('Middleware 2 doSoming');
  await next();
  console.log('Middleware 2 end');
})

app.use(async (ctx, next) => {
  console.log('Middleware 3 doSoming');
  await next();
  console.log('3 end');
})

app.listen(3000, () => {
  console.log('server is running at http://localhost:3000')})Copy the code

Routing koa – the router

The introduction of koa – the router

npm i koa-router -S
Copy the code

Run it after the installation is complete

const Koa = require('koa'// take a look at ('koa-router'Const router = require(const router = require('koa-router')() const app = new Koa()'/', async (ctx, next) => {
    ctx.response.body = `<h1>index page</h1>`
})

router.get('/home', async (ctx, next) => {
    ctx.response.body = '<h1>HOME page</h1>'
})

router.get('/ 404', async (ctx, next) => {
    ctx.response.body = '<h1>404 Not Found</h1>'Use (router.routes()) app.listen(3000, ()=>{console.log()'server is running at http://localhost:3000')})Copy the code

This will be able to achieve a website application, for front-end developers, Node has natural advantages, JS grammar is quite friendly, of course, will certainly be because of the weak language type of pit, step by step learning.