• Node.js 蚕食计划(五)—— Koa 基础项目搭建


    Koa 是由 Express 原班人马打造的超轻量服务端框架

    与 Express 相比,除了自由度更高,可以自行引入中间件之外,更重要的是使用了 ES6 + async,从而避免了回调地狱

    不过也是因为代码升级,所以 Koa2 需要 v7.60 以上的 node.js 环境

     

    一、创建项目

    手动创建一个项目目录,然后快速生成一个 package.json 文件

    npm init -y

    安装 koa    //当前版本 2.4.1

    npm install koa -S

    然后创建一个 app.js

    // app.js
    
    const Koa = require('koa');
    const app = new Koa();
    
    app.use(async ctx => {
      ctx.body = 'Wise Wrong';
    });
    
    app.listen(3000);

    最后在 package.json 中添加启动指令

    一个最基础的 koa 应用就这样完成了

    可以执行 npm start 并在浏览器访问 http://localhost:3000/ 查看效果

     

    如果觉得手动创建项目太过繁琐,可以使用脚手架 koa-generator 来生成项目

    npm install koa-generator -g
    koa2 project_name

    然后在项目下 npm install 安装依赖,npm start 启动项目

    如果是刚接触 koa,建议先看完这篇博客,再使用脚手架工具,这样能更好的理解各个依赖包的作用

     

     

    二、配置路由

    上面 app.js 中有一个 ctx,这是一个 Koa 提供的 Context 对象,封装了 request 和 response

    每一次 HTTP Request 都会创建一个 Context 对象

    我们可以通过 Context.request.path 来获取用户请求的路径,然后通过 Context.response.body 给用户发送内容

    Koa 默认的返回类型是 text/plain,如果要返回一个 html 文件(或者一个模块文件),就需要修改 Context.response.type

    另外,Context.response 可以简写,比如 Context.response.type 简写为 Context.type,Context.response.body 简写为 Context.type

     

    在项目下创建一个存放 html 文件的目录 views,并在该目录下创建一个 index.html,然后修改 app.js

    // app.js
    // 原生路由
    const Koa = require('koa'); const fs = require('fs'); const app = new Koa(); app.use(async (ctx, next) => { if (ctx.request.path === '/index') { ctx.type = 'text/html'; ctx.body = fs.createReadStream('./views/index.html'); } else { await next(); } }); app.listen(3000);

    然后在浏览器中访问 http://localhost:3000/index 就能看到 index.html 页面,而访问别的地址则是 not found

    这样处理 url 显得特别笨拙,所以我们需要引入路由中间件 koa-router

    npm install koa-router -S

    需要注意的是,在导入 koa-router 的时候,需要在末尾加一个括号:

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

    相当于:

    const koaRouter = require('koa-router');
    const router = koaRouter();

    不过也可以通过 new 关键字创建一个 koaRouter 的实例

     

    创建一个 routes 目录,用来存放路由文件,并在目录下创建 index.js

    // routes/index.js
    
    const fs = require('fs');
    const router = require('koa-router')()
    
    router.get('/index', async (ctx, next) => {
      ctx.type = 'text/html';
      ctx.body = fs.createReadStream('./views/index.html');
    });
    
    module.exports = router

    这里还可以使用 prefix 方法,为文件中的所有接口添加一个 baseUrl

    // router.prefix('/about')

     

    修改 app.js

    // app.js
    
    const Koa = require('koa');
    const app = new Koa();
    
    const index = require('./routes/index')
    app.use(index.routes(), index.allowedMethods())
    
    app.listen(3000);

    上面的 allowedMethods 用于校验请求的方法,如果用 post 请求访问 get 接口,就会直接返回失败

    如果在使用了 koa-router 之后,所有的请求都返回 Not Found,请确认是否在入口文件 app.js 中执行了 use,即:

    app.use(router.routes());
    // 或者
    app.use(index.routes(), index.allowedMethods());

     

    另外,还可以在 url 中添加变量,然后通过 Context.params.name 访问

    router.get('/about/:name', async (ctx, next) => {
      ctx.body = `I am ${ctx.params.name}!`;
    });

     

     

    三、静态资源

    在上面的 index.html 中,如果需要引入 css 等静态资源,就需要用到 koa-static

    npm install koa-static -S

    创建一个目录 public 用来存放静态资源

     然后在 app.js 中添加以下代码

    const static = require('koa-static');
    // 将 public 目录设置为静态资源目录
    const main = static(__dirname + '/public');
    app.use(main);

    事实上,这三行代码还可以优化

    app.use(require('koa-static')(__dirname + '/public'));

    然后就能在 index.html 中引入对应的文件了

     

     

    四、模板引擎

    上面的路由是使用 fs 模块直接读取 html 文件

    开发的时候更推荐使用 koa-views 中间件来渲染页面

    npm install koa-views -S

    在 app.js 中将 views 目录设定为模版目录

    const views = require('koa-views')
    app.use(views(__dirname + '/views'));

    然后在路由文件中,就能使用 render 方法了

    // routes/index.js
    
    const router = require('koa-router')()
    
    router.get('/index', async (ctx, next) => {
      await ctx.render('index');
    });
    
    module.exports = router

    以上是直接渲染 html 文件的方法,如果要引入模板引擎,可以添加 extension 字段来设定模版类型

    app.use(views(__dirname + '/views', {
      extension: 'pug'    // 以 pug 模版为例
    }))

     

     

    五、结语

    如果将 Express 看作 webstorm,那么 Koa 就是 sublime

    当 Express 流行的时候,其冗杂的依赖项被很多开发者所诟病

    所以 Express 团队将  Express 拆卸得只剩下最基本的骨架,让开发者自行组装,这就是 Koa

    正如文中所说,从零开始太过繁琐,可以使用脚手架 koa-generato 来快速开发

    不过我更推荐,在熟悉了 Koa 之后,搭一个适合自己项目的脚手架

    不然为何不直接用 Express 呢

    我想这也是 Koa 的官方文档中没有提到 generato 工具的原因吧

     

  • 相关阅读:
    朱刘算法---有向图的最小生成树
    527D Clique Problem 判断一维线段没有两辆相交的最大线段数量
    Tex中的引号
    DAY 96 flask05
    DAY 95 flask04
    DAY 94 flask03
    DAY 93 flask02
    DAY 92 flask01
    DAY 91 爬虫05
    DAY 90 爬虫04
  • 原文地址:https://www.cnblogs.com/wisewrong/p/8202707.html
Copyright © 2020-2023  润新知