Node.js 开发Rest的Api示例项目(二)
【摘要】
app.js
'use strict'; console.log('Hello world');const Koa = require('koa');const bodyParser = require('koa-bodyparser'); const app = new Koa();const controller = require...
app.js
-
'use strict';
-
-
console.log('Hello world');
-
const Koa = require('koa');
-
const bodyParser = require('koa-bodyparser');
-
-
const app = new Koa();
-
const controller = require('./controller');
-
// parse request body:
-
app.use(bodyParser());
-
// add controller:
-
app.use(controller());
-
app.listen(5000);
-
console.log('app started at port 5000...');
controller.js
-
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) {
-
var fs = require('fs');
-
var files = fs.readdirSync(__dirname + '\\controllers');
-
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\\' + 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();
-
};
controllers文件夹下的接口接口文件:
./controllers/hello.js
-
'use strict'
-
module.exports = {
-
'POST /hello/:name': async (ctx, next) => {
-
var name = ctx.request.body.name || '';
-
ctx.response.body = `<h1>Hello post, ${name}!</h1>`;
-
}
-
};
./controllers/index.js
-
'use strict'
-
-
var fn_index = async (ctx, next) => {
-
ctx.response.body = `<h1>Index</h1>
-
<form action="/signin" method="post">
-
<p>Name: <input name="name" value="koa"></p>
-
<p>Password: <input name="password" type="password"></p>
-
<p><input type="submit" value="Submit"></p>
-
</form>`;
-
};
-
-
var fn_signin = async (ctx, next) => {
-
var
-
name = ctx.request.body.name || '',
-
password = ctx.request.body.password || '';
-
console.log(`signin with name: ${name}, password: ${password}`);
-
if (name === 'koa' && password === '12345') {
-
ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
-
} else {
-
ctx.response.body = `<h1>Login failed!</h1>
-
<p><a href="/">Try again</a></p>`;
-
}
-
};
-
-
-
-
module.exports = {
-
'GET /': fn_index,
-
'POST /signin': fn_signin
-
};
文章来源: zzzili.blog.csdn.net,作者:清雨小竹,版权归原作者所有,如需转载,请联系作者。
原文链接:zzzili.blog.csdn.net/article/details/79305544
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)