使用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 就能运行啦

猜你喜欢

转载自blog.csdn.net/Alive_tree/article/details/105727044