Node.js 不正经学习(第四天 koa.js学习)

Koa介绍

Koa 是下一代的 Node.js 的 Web 框架。由 Express 团队设计。旨在提供一个更小型、更富有表现力、更可靠的 Web 应用和 API 的开发基础。
Koa可以通过生成器摆脱回调,极大地改进错误处理。Koa核心不绑定任何中间件,但提供了优雅的一组可以快速和愉悦地编写服务器应用的方法。

安装

Koa 依赖 node v7.6.0 或 ES2015及更高版本和 async 方法支持.

使用npm安装

npm i koa

引入

导入koa包,并创建app

/**
 * 引入框架
 */
const Koa = require('koa');
// 创建app对象
const app = new Koa();

使用

  • 第一个服务
// 监听请求并返回响应,这里响应字符串 "hello , index" 
app.use(async context => {
    context.body = 'hello , index';
});


//启动服务,绑定端口
app.listen(3000, () => {
    console.log('服务启动成功!');
});

use方法

use方法实际上执行顺序是从上往下执行,但是当使用await next(); 之后默认会将use关联的方法压入栈中,先压入得方法后执行。类似于java中阻塞线程得等待。

  • 可以使用该特性制作N多中间层,进行数据的处理及业务逻辑的封装。
/**
 * 拦截请求,打出log日志。
 * 将该中间层放在栈的最顶层。顺序await之前从上往下,阻塞之后从下往上走。
 */
app.use(async (context, next) => {
    // 等待上层执行完成
    await next();
    // 获取本次响应的时间
    const responseTime = context.response.get('X-Response-Time');
    // 打印
    console.log(`${context.method} :: ${responseTime} - ${context.url}`);
});

/**
 * 往请求响应头中写入响应时间
 */
app.use(async (context, next) => {
    // 请求之前记录当前时间
    const start = Date.now();
    // 等待上层执行完成
    await next();
    // 响应之后计算等待时间单位毫秒
    const ms = Date.now() - start;
    context.set('X-Response-Time', `${ms}ms`);
});

路由模块 koa-router

路由模块使用koa-route,该模块可以简单高效的完成接口对象的抽取及绑定。
参考

  • 使用npm安装
npm install koa-router
  • 引入koa-router
/**
 * 引入第三方路由模块
 */
const _ = require('koa-route');
var router = new _();
  • 使用,路由集合方式
// 请求路由集合
const pets = {
    '/about': context => {
        context.response.type = 'html';
        context.response.body = '关于页面';
    },
    '/login': context => {
        context.response.type = 'html';
        context.response.body = '
登录页面
'; }, '/reg': context => { context.response.body = '注册页面'; }, '/mine': context => { context.response.type = 'html'; context.response.body = '
个人中心
'; }, '/show/:name': (context, name) => { context.response.type = 'html'; context.response.body = '
个人中心 ' + `${name}` + '
'; } }; // 添加路由 Object.keys(pets).forEach(function (key) { app.use(_.get(key, pets[key])); });
  • 单个路由过滤
// 路由home路径的get请求
router.get('/home', async (ctx, next) => {
    ctx.body = 'we are at home!';
    return next();
}, async (ctx, next) => {
    ctx.body = 'home 2';
});
// 对应HTTP对应的动作,all代表所有的请求方式
router
    .get('/', async (ctx, next) => {
        ctx.body = 'Hello World!';
    })
    .post('/users', async (ctx, next) => {

    })
    .put('/users/:id', async (ctx, next) => {

    })
    .del('/users/:id', async (ctx, next) => {

    })
    .all('/users/:id', async (ctx, next) => {

    });

// 将路径路由添加到app
app
    .use(router.routes())
    .use(router.allowedMethods());

附上Demo代码

/**
 * 引入框架
 */
const Koa = require('koa');
// 创建app对象
const app = new Koa();

/**
 * 引入第三方路由模块
 */
const _ = require('koa-route');
var router = new _();



/**
 * 拦截请求,打出log日志。
 * 将该中间层放在栈的最顶层。顺序await之前从上往下,阻塞之后从下往上走。
 */
app.use(async (context, next) => {
    // 等待上层执行完成
    await next();
    // 获取本次响应的时间
    const responseTime = context.response.get('X-Response-Time');
    // 打印
    console.log(`${context.method} :: ${responseTime} - ${context.url}`);
});

/**
 * 往请求响应头中写入响应时间
 */
app.use(async (context, next) => {
    // 请求之前记录当前时间
    const start = Date.now();
    // 等待上层执行完成
    await next();
    // 响应之后计算等待时间单位毫秒
    const ms = Date.now() - start;
    context.set('X-Response-Time', `${ms}ms`);
});


// 请求路由集合
const pets = {
    '/about': context => {
        context.response.type = 'html';
        context.response.body = '关于页面';
    },
    '/login': context => {
        context.response.type = 'html';
        context.response.body = '
登录页面
'; }, '/reg': context => { context.response.body = '注册页面'; }, '/mine': context => { context.response.type = 'html'; context.response.body = '
个人中心
'; }, '/show/:name': (context, name) => { context.response.type = 'html'; context.response.body = '
个人中心 ' + `${name}` + '
'; } }; // 添加路由 Object.keys(pets).forEach(function (key) { app.use(_.get(key, pets[key])); }); // 路由home路径的get请求 router.get('/home', async (ctx, next) => { ctx.body = 'we are at home!'; return next(); }, async (ctx, next) => { ctx.body = 'home 2'; }); // 对应HTTP对应的动作,all代表所有的请求方式 router .get('/', async (ctx, next) => { ctx.body = 'Hello World!'; }) .post('/users', async (ctx, next) => { }) .put('/users/:id', async (ctx, next) => { }) .del('/users/:id', async (ctx, next) => { }) .all('/users/:id', async (ctx, next) => { }); // 将路径路由添加到app app .use(router.routes()) .use(router.allowedMethods()); app.use(async context => { context.body = 'hello , index'; }); app.listen(3000, () => { console.log('服务启动成功!'); });

你可能感兴趣的:(Node.js 不正经学习(第四天 koa.js学习))