美文网首页
Koa | 2. koa-bodyparser的使用

Koa | 2. koa-bodyparser的使用

作者: ShadowFieldEric | 来源:发表于2021-01-27 13:43 被阅读0次

    安装模块

    npm install koa-bodyparser
    

    或者配置文件package.json中依赖配置如下:

    {
      "dependencies": {
        "koa": "^2.13.1",
        "koa-bodyparser": "^4.3.0",
        "koa-router": "^10.0.0",
        ...
      },
      ...
    }
    

    利用koa-bodyparser来处理POST请求参数,代码如下:

    const Koa = require('koa');
    const Router = require('koa-router');
    const BodyParser = require('koa-bodyparser');
    
    // 创建一个Koa对象表示web app本身:
    const app = new Koa();
    const router = new Router();
    const bodyparser= new BodyParser();
    
    // 对于任何请求,app将调用该异步函数处理请求:
    app.use(async (ctx, next) => {
      console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
      await next();
    });
    
    // middleware的顺序很重要,这个koa-bodyparser必须在router之前被注册到app对象上
    app.use(bodyparser);
    
    router.get('/', async (ctx, next) => {
      ctx.response.body = `<h1>Hello, Koa2</h1>`;
    });
    
    router.get('/hello/:name', async (ctx, next) => {
      let name = ctx.params.name;
      ctx.response.body = `<h1>Hello, ${name}</h1>`
    });
    
    router.post('/login', async (ctx, next) => {
      if (ctx.request == null || ctx.request.body == null) {
        ctx.response.body = {
          code: 10001,
          success: false,
          message: 'Login failure, please check form-data type.'
        }
        return;
      }
    
      let username = ctx.request.body.username || '';
      let password = ctx.request.body.password || '';
      console.log(`/login with name: ${username}, password: ${password}`);
      if (username === 'koa' && password === '123456') {
        ctx.response.body = {
          code: 20000,
          success: true,
          message: 'Login success.'
        }
      } else {
        ctx.response.body = {
          code: 10017,
          success: false,
          message: 'Login failure, please check username or password.'
        }
      }
    });
    
    app.use(router.routes());
    
    // 在端口3000监听:
    app.listen(3000);
    console.log('app started at port 3000...');
    

    相关文章

      网友评论

          本文标题:Koa | 2. koa-bodyparser的使用

          本文链接:https://www.haomeiwen.com/subject/godeaktx.html