nodejs(2)—koa2(GET,POST)

  1. 安装koa npm i [email protected]或者在packge.json文件 dependencies字段中加入 "koa":"2.0.0"字段,npm install 当前工程nodes_modules目录中会自动添加koa模块
  2. 新建app.js
  3. 在app.js中添加如下代码

const Koa =require('koa');
const app=new Koa();
app.use(async (ctx,next)=>{
    console.log(`Process ${ctx.request.method} ${ctx.request.url} ....`);
    
    await next(); 
});
app.use(async (ctx,next)=>{
    const {path,body}=ctx.request;
    if(path==='/test'){
        body='Test page'
    }else{
        await next();
    }
});
app.listen(3000);
console.log('app started at port 3000');

4.运行 node app.js ,在控制台上会显示出app started at port 3000

上述代码缺点:新增链接都会再app.js文件中添加,导致后续代码量越来越大,并且难以维护

  1. koa-router koa路由的作用是使url从代码中分离出来,单独维护,不需要在异步函数中进行判断,安装方式见1


const router=require('koa-router')();

router.get('/test',async (ctx,next)=>{
    ......
});
  1. 上述只适用于get方式,post方式需要在安装koa-bodyparser


const bodyParser=require('koa=bodyparser');

router.post('/signin',async (ctx,next)=>{
    const {request,reponse}=ctx;
    const {name,password}=request.body;
    ......
})
  1. 上述改造虽然使代码结构更加清晰,但是比没有解决最开始的app.js代码量过多的问题。要解决app.js代码量过多的问题,需要如下操作:

新建controllers.js文件,负责遍历在controller文件夹下的以.js结尾的文件,并且引入文件添加在router中

const fs = require('fs');

function addMapping(router, mapping) {
    for (var url in mapping) {
        if (url.startsWith('GET')) {
            var path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register url mapping:GET ${path}`);
        } else if (url.startsWith('POST')) {
            var path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping:POST ${path}`);
        } else {
            console.log(`invalid url:${url}`);
        }
    }
}

function addControllers(router) {
    const files = fs.readdirSync(__dirname + '/controllers');
    // 过滤出js文件
    const js_files = files.filter(f => {
        return f.endsWith('.js');
    });
    // 处理每个js文件
    for (var f of js_files) {
        console.log(`process controller:${f}`);
        // 引入js文件
        let mapping = require(__dirname + '/controllers/' + f);
        addMapping(router, mapping);
    }
}
module.exports = function(dir) {
    let controllers_dir = dir || 'controllers',
        router = require('koa-router')();
    addControllers(router, controllers_dir);
    return router.routes();
}

新建controller文件夹,js文件主要是异步处理函数

const fn_index=async (ctx,next)=>{
    ctx.response.body = `

Index

Name:

Password:

`; }; const fn_signin=async (ctx,next)=>{ const { request, response } = ctx; const { name, password } = request.body; console.log(`sigin with name:${name},password:${password}`); if (name === 'koa' && password === '12345') { response.body = `

Welcome,${name}

`; } else { response.body = `

Login failed!

Try again

`; } }; const fn_hello=async (ctx,next) =>{ const name=ctx.params.name; ctx.response.body=`

Hello,${name}!

`; } module.exports={ 'GET /':fn_index, 'POST /signin':fn_signin, 'GET /hello/:name':fn_hello };
  1. 至此拆分结束 运行node app.js
  2. git详细代码地址 https://github.com/jdkwky/webstudydeep/tree/webstudydeep/hello-koa

==参考:廖雪峰nodejs教程==

你可能感兴趣的:(nodejs(2)—koa2(GET,POST))