美文网首页
koa2试水

koa2试水

作者: Yard | 来源:发表于2017-04-14 14:03 被阅读91次

koa2出来已经很长一段时间了,之前一直没有遇上可以练手的项目,这次刚好有了机会,正好折腾一下。

安装

koa2需要7.6.0及以上的node版本,目的是为了支持async await语法,不需要babel支持(7.6.0以下如果使用async await语法需要babel配置)。

官方推荐使用nvm去做node的版本管理。(因之前遇到的一些坑,而且对于版本管理的需求不是很大,笔者都是直接覆盖安装最新版本。)

yarn add koa

(当然也可以使用npm)

简单使用

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

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

// 监听端口3000
app.listen(3000);
console.log('打开127.0.0.1:3000查看');

中间件模式

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

// x-response-time

app.use(async function (ctx, next) {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async function (ctx, next) {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

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

app.listen(3000);

通过async await 来实现中间件的同步模式,由最上面的async开始 一只进入下一个await


中间件模式

路由模块

使用koa-router来实现路由

yarn add koa-router

独立的index.js路由文件

const Router = require('koa-router');
const users = require('./users');

const myRouter = new Router();
myRouter.use('/users', users.routes(), users.allowedMethods());


myRouter.get('/', async (ctx) => {
    ctx.body = 'Hello Worlddjlhud h!';
});

module.exports = myRouter;

app.js

const myRouter = require('./routers/index');
app
  .use(myRouter.routes())
  .use(myRouter.allowedMethods());

一个简单的koa2服务器就搭建好了

附上github地址https://github.com/YardWill/Hydropower-Station-monitoring(https://github.com/YardWill/Hydropower-Station-monitoring)

相关文章

  • koa2试水

    koa2出来已经很长一段时间了,之前一直没有遇上可以练手的项目,这次刚好有了机会,正好折腾一下。 安装 koa2需...

  • 使用koa2+mongodb+ava构建RESTful api并

    初涉nodejs后台开发,在得知express和koa是同一个团队开发之后果断选择了更前沿的koa2试水。结果发现...

  • 昆仑能源新闻宣传培训班鸣锣开班 - 草稿

    试水!试水!试水!

  • 2018-01-30

    试水试水

  • koa2入门系列

    koa2入门系列(一) koa2入门系列(二) koa2入门系列(三) koa2入门系列(四) koa2入门系列(...

  • 试水

    “兄弟啊,昨天约会怎么样?”林锦城趴在宿舍的床上,玩着手机心不在焉的问。 顾泽看了看他的臀部,默默吞了口口水,将表...

  • 试水

    哦这是正文? 哈哈哈哈哈分割线 哦呦有意思

  • 试水

    我先试一下水,在这里写耽美文会有人看不。^o^ 人设:受是一个集可爱呆萌傲娇于一身的狐妖。 攻是一位不务正业的道士...

  • 试水

    就是来试试

  • 试水

网友评论

      本文标题:koa2试水

      本文链接:https://www.haomeiwen.com/subject/vfswattx.html