前端快速入门Koa.js

前言

Nodejs 提供了 http 能力,我们通过如下代码可以快速创建一个http server服务

const http = require('http');

http
  .createServer((req, res) => {
    res.write('hello\n');
    res.end();
  })
  .listen(3000);

使用nodejs提供的原生能力启动一个http server并不麻烦,但是拓展额外的能力就比较麻烦,比如支持路由router,静态资源,页面模板等。

插件机制是目前非常流行的拓展能力的设计方式,Koa框架是基于插件机制封装出来的一个Node HTTP框架,我将简单记录一下Koa的插件机制以及丰富的插件。

快速启动

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

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

app.listen(9999,()=>{
    console.log('App start on port: 9999')
});
// package.json
{
 "scripts": {
    "dev": "node app.js"
  }
}

中间件Middleware(洋葱模型)

通过 Koa.use 将中间件注册到 koa应用中,中间件可以注册N个

我们可以通过插件机制个性化功能,提供给别人复用

中间件格式 async (ctx,next)=>{}

  • ctx => context对象,包含request,response对象,我们可以通过ctx来处理自己的业务需求

  • next ,promise对象,可以通过await next(),让程序执行下一个中间件,执行完后再执行当前中间件next下面的逻辑

const Koa = require('koa');

const app = new Koa();

app.use(async(ctx,next)=>{
  console.log('middleware one in')
  await next();
  console.log('middleware one out')
})

app.use(async(ctx,next)=>{
  console.log('middleware two in')
  await next();
  console.log('middleware two out')
})

app.use(async(ctx,next)=>{
  console.log('middleware three in')
  await next();
  console.log('middleware three out')
})

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行结果

middleware one in
middleware two in
middleware three in
middleware three out
middleware two out
middleware one out

中间件运行过程

常用中间件

Koa Router

作为一个HTTP server,处理不同path的请求是最常见的问题,koa router就是专门处理路由分发的中间件

主程序

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

router.get('/',async(ctx)=>{
  ctx.type = 'html';
  ctx.body = '<h1>hello world!</h1>';
})

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

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行结果

属性简介

Router实例上提供了http的多种请求方式 get post put delete等等。router的请求方法会接受两个参数,第一个参数是匹配的请求的路径 path,第二个参数是处理逻辑的函数。

Router的 routes,allowedMethods方法返回参数,是koa实例接受中间件格式。

Koa View

页面渲染器,支持多种成熟的模版解析引擎。

npm add koa-view ejs

主程序代码

//app.js
const Koa = require('koa');
const Router = require('koa-router');
const views = require('koa-views');

const app = new Koa();
const router = new Router();

app.use(views(__dirname + '/views', {
  map: {
    html: 'ejs'
  }
}))



router.get('/home',async(ctx)=>{
  await ctx.render('home',{words:'欢迎你'})
})

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

app.listen(9999, () => {
  console.log("app started! port:9999");
});

html模版

// views/home.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>乐闻世界</title>
</head>

<body>
    乐闻世界<%= words %>
</body>

</html>

运行效果

Koa Static

koa 支持静态资源的请求

相关依赖

yarn add koa-static

主程序

const Koa = require('koa');
const static = require('koa-static');

const app = new Koa();

app.use(static(__dirname + '/statics'))

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行效果

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

乐闻x

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值