1. koa2 的安装与使用
- 新建文件夹
- npm init
- npm i koa --save
代码演示
新建 index.js 文件
const Koa = require('koa') // commonjs 模块化规范
const app = new Koa()
// ctx context 上下文
app.use(async (ctx) => {
ctx.body = 'hello world'
})
app.listen(3000) // web server 监听的 3000 端口
2. koa2 的环境搭建
使用脚手架 koa-generator 创建 koa2 项目
介绍项目
在项目中新建一个路由
-
使用脚手架 koa-generator 创建 koa2 项目
- npm install -g koa-generator (全局安装脚手架)
- koa2 test4 (将 koa2 安装在 test4 文件夹下)
- 在 test4 文件夹下 npm install
- 启动 npm run dev
- 浏览器 localhost:3000 查看
-
项目介绍
app.js 中
-
onerror(app) //错误处理器
-
bodyparser() 用于 request body 转换
-
app.use(require(‘koa-static’)(__dirname + ‘/public’)) //***静态文件服务***的功能
- 表示在 public 文件夹下的文件,都可以通过:
localhost:3000/images/1.jpg
这种方式来访问这个源文件
-
app.use(views(__dirname + ‘/views’, { // 服务端模板引擎
extension: ‘pug’
}))
-
-
新建路由
-
定义路由文件
-
routes 文件夹下新建 comments.js
-
comments.js 代码:
const router = require('koa-router')() router.prefix('/api') // 前缀 // 定义路由:模拟获取留言板列表 router.get('/list', async (ctx) => { ctx.body = 'api list' }) // 定义路由:模拟创建留言内容 router.post('/create', async (ctx) => { ctx.body = 'api create' }) module.exports = router // 输出
-
-
-
在 app.js 文件中引入路由
const comments = require('./routes/comments')
-
注册路由
`app.use(comments.routes(), comments.allowedMethods())