使用koa-router

koa-router是使用koa框架的时候不可少的中间件,但是使用起来是比较简单的,本文就简单介绍一下koa-router的使用。
因为网址的路径不同,所以我们要对输入的网址进行判断,从而返回不同的内容。

1、不使用koa-router的方法

const Koa = require('koa');
const app = new Koa();

const main = function (ctx) {
    ctx.response.body = 'hello';
    if(ctx.request.path != '/'){
        ctx.response.type = 'html';
        ctx.response.body = '<a href="/">Index Page</a>'
    }else{
        ctx.response.body = 'hello cxx';
    }
};

app.use(main);

app.listen(3001);

写的比较麻烦,如果路径多了使用不是很方便。

2、使用koa-router方法

第一步、在终端去下载koa-router 插件(注意是koa-router 不是koa-Router)

koa install -S koa-router

这时候我们package.json文件里面就会有

 "dependencies": {
    "koa": "^2.11.0",
    "koa-router": "^8.0.8"
  }

说明我们安装成功
第二步、引用

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

router.get('/',function (ctx) {
    console.log(ctx);
    ctx.body = 'hello world';
});
router.get('/api',function (ctx) {
    console.log(ctx);
    ctx.body = 'hello routerApi';
});

app.use(router.routes())
    .use(router.allowedMethods())   //把前面所有定义的方法添加到app应用上去

app.listen(3000);

在文件上点击run 就能运行啦

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值