@H_3010@Koa 是由 Express 原班人马打造的超轻量服务端框架
@H3010@与 Express 相比,除了自由度更高,可以自行引入中间件之外,更重要的是使用了 ES6 + async,从而避免了回调地狱
@H301_0@不过也是因为代码升级,所以 Koa2 需要 v7.60 以上的 node.js 环境
一、创建项目
@H_301_0@手动创建一个项目目录,然后快速生成一个package.json 文件const app = new Koa();
app.use(async ctx => {
ctx.body = 'Wise Wrong';
});
app.listen(3000);
二、配置路由
@H_301_0@上面 app.js 中有一个 ctx,这是一个 Koa 提供的 Context 对象,封装了 request 和 response @H_301_0@每一次HTTP Request 都会创建一个 Context 对象 @H_301_0@我们可以通过 Context.request.path 来获取用户请求的路径,然后通过 Context.response.body 给用户发送内容 @H_301_0@Koa 默认的返回类型是 text/plain,如果要返回一个 html 文件(或者一个模块文件),就需要修改 Context.response.type @H_301_0@另外,Context.response 可以简写,比如 Context.response.type 简写为 Context.type,Context.response.body 简写为 Context.type @H_301_0@在项目下创建一个存放 html 文件的目录 views,并在该目录下创建一个 index.html,然后修改 app.jsconst 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);
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
// router.prefix('/about')
修改 app.js
const app = new Koa();
const index = require('./routes/index')
app.use(index.routes(),index.allowedMethods())
app.listen(3000);
另外,还可以在 url 中添加变量,然后通过 Context.params.name 访问
三、静态资源
在上面的 index.html 中,如果需要引入 css 等静态资源,就需要用到
四、模板引擎
@H_301_0@上面的路由是使用 fs 模块直接读取 html 文件 @H_301_0@开发的时候更推荐使用 nofollow" target="_blank" href="https://www.npmjs.com/package/koa-views">koa-views 中间件来渲染页面router.get('/index',next) => {
await ctx.render('index');
});
module.exports = router