koa自动加载路由不区分http请求方法 1. [代码] [PHP]代码 作者官网: http://www.wemallshop.com 2. [代码] README.md var app = require('koa')();var koaResourceRouter = require('koa-resource-router');app.use(koaResourceRouter
1. [代码][PHP]代码
作者官网: http://www.wemallshop.com
2. [代码]README.md
var app = require('koa')(); var koaResourceRouter = require('koa-resource-router'); app.use(koaResourceRouter(app, { root: './app/controller', suffix: '.js', action: 'index' })); exports.index = function*(ctx, next){ console.log(ctx); console.log(ctx.query); console.log(ctx.params); }
3. [代码]index.js
var path = require('path'); var fs = require('fs'); module.exports = function (app, options) { if (!options || typeof options.root === 'string') { if (!path.isAbsolute(options.root)) { options.root = path.join(process.cwd(), options.root); } } else { throw Error('root must be specified'); } options.suffix = options.suffix || '.js'; options.action = options.action || 'index'; return function* koaResource(next) { var url = this.url.split('?'); var querystring = url[1]; var url = url[0].split(path.sep); for (var i = 0; i < url.length; i++) { if (i == url.length - 2) { url[i] += options.suffix; } } var _url = ''; var params = []; var action = options.action; for (var i = 0; i < url.length - 1; i++) { if (!url[i]) { continue; } var exists = fs.existsSync(options.root + _url + '/' + url[i]); if (exists) { _url += '/' + url[i]; } else { params.push(url[i]); } if (url.length - 2 == i && !exists) { throw Error('Not Found'); } } this.params = params; this.querystring = querystring; var _require = require(path.join(options.root, _url)); yield _require[action](this, next); yield next; }; };
4. [代码]package.json
{ "name": "koa-http-router", "version": "1.0.1", "description": "koa http router", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git+https://github.com/einsqing/koa-http-router.git" }, "keywords": [ "koa", "koa-router", "koa-http-router", "router" ], "author": "www.wemallshop.com", "license": "ISC", "bugs": { "url": "https://github.com/einsqing/koa-http-router/issues" }, "homepage": "https://github.com/einsqing/koa-http-router#readme", "dependencies": { } }