初始化

This commit is contained in:
pplokijuhyg 2019-10-28 08:21:03 +08:00
parent d542070a63
commit cd55165b67
6 changed files with 2355 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
node_modules

18
app.js Normal file
View File

@ -0,0 +1,18 @@
const Koa = require("koa");
const requter = require("./router.js");
// console.log(requter)
// import requter from "./bin/router"
const app = new Koa();
app.use(async (ctx,next)=>{
// await next();
ctx.response.body = {a:1};
// next()
console.log("执行")
});
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());
// console.log(requter())
app.use(requter());
app.listen(3000);

10
controllers/login.js Normal file
View File

@ -0,0 +1,10 @@
var login = async (ctx, next) => {
// var name = ctx.params.name;
// ctx.response.body = `<h1>Hello, ${name}!</h1>`;
ctx.response.body="这是login"
next()
};
module.exports = {
'GET /login': login
};

2277
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

12
package.json Normal file
View File

@ -0,0 +1,12 @@
{
"scripts": {
"start": "node app.js"
},
"dependencies": {
"fs": "0.0.1-security",
"koa": "^2.10.0",
"koa-bodyparser": "^4.2.1",
"koa-router": "^7.4.0",
"nunjucks": "^3.2.0"
}
}

37
router.js Normal file
View File

@ -0,0 +1,37 @@
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,controllers_dir) {
var files = fs.readdirSync(__dirname +"/"+ controllers_dir);
var js_files = files.filter((f) => {
return f.endsWith('.js');
});
for (var f of js_files) {
console.log(`process controller: ${f}...`);
let mapping = require(__dirname + `/${controllers_dir}/` + f);
addMapping(router, mapping);
}
}
module.exports = function (dir) {
let
controllers_dir = dir || 'controllers', // 如果不传参数,扫描目录默认为'controllers'
router = require('koa-router')();
addControllers(router, controllers_dir);
return router.routes();
// return 1;
};