1. Koa框架简介:
koa 是由 Express 原班人马打造的,致力于成为一个更小、更富有表现力、更健壮的Web 框架。 使用 koa 编写 web 应用,可以免除重复繁琐的回调函数嵌套, 并极大地提升错误处理的效率。koa 不在内核方法中绑定任何中间件, 它仅仅提供了一个轻量优雅的函数库,使得编写 Web 应用变得得心应手。开发思路和 express 差不多,最大的特点就是可以避免异步嵌套。
2. 安装:
mkdir koa-demo-01
cd koa-demo-01
npm install koa --save
npm install koa-router koa-static-cache --save
3. 图示:
4. 代码:
const Koa = require('koa'); // 1.引入模块
const koaStaticCache = require('koa-static-cache');
const Router = require('koa-router');
const app = new Koa(); // 2.实例化
const router = new Router();
app.use(koaStaticCache(__dirname + '/static', { // 3.配置静态资源
// root:'',
prefix: '/public', // 例如 localhost:3000/public/index.html
maxAge: 365 * 24 * 60 * 60,
}))
router.get('/', (ctx, next) => { // 4. 配置路由
ctx.body = 'hello koa' // 响应返回数据
})
router.get('/xxx', (ctx, next) => {
ctx.response.redirect('/'); // 重定向
})
// 5.子路由 方式一
const userRouter = new Router();
userRouter.get('/', (ctx, next) => { // localhost:3000/user
ctx.body = '/user'
})
userRouter.get('/address', (ctx, next) => { // localhost:3000/user/address
ctx.body = '/user/address'
})
router.use('/user', userRouter.routes()); // 注册路由
// 6.子路由 方式二
const itemRouter = new Router({
prefix: '/item'
})
itemRouter.get('/', (ctx, next) => { // localhost:3000/item/list
ctx.body = '/item'
})
itemRouter.get('/list', (ctx, next) => { // localhost:3000/item/list
ctx.body = '/item/list'
})
app.use(itemRouter.routes()); // 注册路由
// 7.动态路由
const goodsRouter = new Router({})
goodsRouter.get('/goods/:id', (ctx, next) => { // localhost:3000/goods/12345
ctx.body = `goods: ${ctx.params.id}`
})
app.use(goodsRouter.routes());
// 路由重定向 访问localhost:3000/admin 重定向至 localhost:3000/user
router.redirect('/admin', '/user', 301);
app.use(router.routes()) // 注册 路由
app.use(router.allowedMethods()) // 路由 错误 处理
app.listen(3000)
5. 启动:
node app.js