【Koa】Koa封装前端发送的各种URL请求,进行业务分离

1,controller.js:根据不同的URL方式,匹配对应的JS控制器

const fs = require('fs');

// 捕获请求方式,并匹配路由router
function addMapping(router, mapping) {
  for (var url in mapping) {
    if (url.startsWith('GET ')) { // 捕获get
      var path = url.substring(4);
      router.get(path, mapping[url]);
      console.log(`register URL mapping: GET ${path}`);
    } else if (url.startsWith('POST ')) { // 捕获post
      var path = url.substring(5);
      router.post(path, mapping[url]);
      console.log(`register URL mapping: POST ${path}`);
    } else if (url.startsWith('PUT ')) { // 捕获put
      var path = url.substring(4);
      router.put(path, mapping[url]);
      console.log(`register URL mapping: PUT ${path}`);
    } else if (url.startsWith('DELETE ')) { // 捕获delete
      var path = url.substring(7);
      router.del(path, mapping[url]);
      console.log(`register URL mapping: DELETE ${path}`);
    } else {
      console.log(`invalid URL: ${url}`);
    }
  }
}

// 导入目录请求封装的js
function addControllers(router, dir) {
  fs.readdirSync(__dirname + '/' + dir).filter((f) => {
    return f.endsWith('.js');
  }).forEach((f) => {
    console.log(`process controller: ${f}...`);
    let mapping = require(__dirname + '/' + dir + '/' + f);
    addMapping(router, mapping);
  });
}

// 把各种请求方式下,解析的目录控制器暴露出去
module.exports = function (dir) {
  let controllers_dir = dir || 'controllers',
      router = require('koa-router')();
  addControllers(router, controllers_dir);
  return router.routes();
};

2,处理不同URL的controller:

// 处理hello相关URL hello.js

// get /hello:name
var fn_hello = async (ctx, next) => {
  var name = ctx.params.name;
  ctx.response.body = `

Hello, ${name}!

`; }; module.exports = { 'GET /hello/:name': fn_hello }; // 处理index相关URL index.js // get / 首页请求 var fn_index = async (ctx, next) => { ctx.response.body = `

首页

Name:

Password:

`; }; // post signin表单提交 var fn_signin = async (ctx, next) => { var name = ctx.request.body.name || ''; var password = ctx.request.body.password || ''; console.log(`signin with name: ${name}, password: ${password}`); if (name === 'koa' && password === '12345') { ctx.response.body = `

Welcome, ${name}!

`; } else { ctx.response.body = `

Login failed!

Try again

`; } }; module.exports = { 'GET /': fn_index, 'POST /signin': fn_signin };

3,主入口app.js调用

const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const app = new Koa();

// 监听请求的日志
app.use(async (ctx, next) => {
  console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
  await next();
});

// 使用bodyParser,post请求参数解析
app.use(bodyParser());
// 使用分离的url处理控制器
app.use(controller());

app.listen(3001);
console.log('app started at port 3001...');

 

你可能感兴趣的:(NodeJS,Koa)