Skip to content

使用koa-router

下载 koa-router

$ npm i koa-router --save
或者
$ yarn add koa-router
或者
$ pnpm install koa-router

使用koa-router

js
const Koa = require('koa')
const koaRouter = require('koa-router');
const app = new Koa()
// 创建路由实例
const router = new koaRouter()


// 注册路由: 
// /api 、
//  /
// /api/update
router.get('/', (ctx) => {
    ctx.body = 'hello koa'
    console.log('index')
})

// 注册get请求
router.get('/api', async (ctx, next) => {
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa'
        }
    }
})

// 注册post 请求
router.post('/api/update', async (ctx, next) => {
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa post'
        }
    }
})

// 注册路由
app.use(router.routes())
// 自动丰富 response 相应头,当未设置响应状态(status)的时候自动设置,在所有路由中间件最后设置(全局,推荐),也可以设置具体某一个路由(局部),
//例如:router.get('/index', router.allowedMethods()); 这相当于当访问 /index 时才设置
app.use(router.allowedMethods())

app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})

浏览器输入url 是get请求方法不被允许

image-20230712225829319

使用ApiPost 发送post 请求

image-20230712225926811

接收get请求参数

js
router.get('/api', async (ctx, next) => {
    const result = ctx.query;
    console.log(ctx.query) // 接收get请求url(query) 参数
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa'
        },
        params: result
    }
})

image-20230712230814463

获取post请求参数

post 参数不能直接获取需要通过监听流的方式获取

解决办法: 通过安装koa-bodyparser 获取

shell
$ npm i koa-bodyparser --save

使用方式:

js
const Koa = require('koa')
const koaRouter = require('koa-router');
const app = new Koa()
const router = new koaRouter()
// 使用 koa-bodyparser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
js
router.post('/api/update', async (ctx, next) => {
   // 获取post参数
    const result = ctx.request.body;
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa post'
        },
        body: result
    }
})

post请求获取url 参数(跟get请求一致)

js

router.post('/api/update', async (ctx, next) => {
    const query = ctx.query;
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa post'
        },
        query
    }
})

get 请求也可以获取body 参数

js
router.get('/api', async (ctx, next) => {
    const result = ctx.query;
    console.log(ctx.query)
    console.log(ctx.request.body)
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa'
        },
        params: result,
        body: ctx.request.body
    }
})

image-20230712233007392

TIP

说明get 请求和post请求没有区别

完整代码

js
const Koa = require('koa')
const koaRouter = require('koa-router');
const app = new Koa()
const router = new koaRouter()
const bodyParser = require('koa-bodyparser')

app.use(bodyParser())

// 通过cors 解决跨域
app.use(async (ctx, next) => {
    ctx.set('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
    ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    if (ctx.method == 'OPTIONS') {
        ctx.body = 200;
    } else {
        await next();
    }
});

router.get('/', (ctx) => {
    ctx.body = 'hello koa'
    console.log('index')
})
router.get('/api', async (ctx, next) => {
    const result = ctx.query;
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa'
        },
        params: result,
    }
})

router.post('/api/update', async (ctx, next) => {
    const result = ctx.request.body;
    const name = result.name1;

    ctx.body = {
        code: 0,
        data: {
            name: name + "xxxx"
        }
    }
    ctx.body = {
        code: 0,
        msg: 'success',
        data: {
            name: 'koa post'
        },
        body: result
    }
})

// 注册路由
app.use(router.routes())
// 自动丰富 response 相应头,当未设置响应状态(status)的时候自动设置,在所有路由中间件最后设置(全局,推荐),也可以设置具体某一个路由(局部),
//例如:router.get('/index', router.allowedMethods()); 这相当于当访问 /index 时才设置
app.use(router.allowedMethods())

app.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})

前端知识体系 · wcrane