Koa框架搭建 - 静态资源配置 - 路由配置

查看更多资源

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

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值